How to avoid Scanner from eof and keep him alive

时间:2019-04-16 22:26:58

标签: java

could you tell me is there any solution to keep Scanner alive after ctrl+d (eof)?

I have this

static public int getInt(String errorText){
    Scanner scan = new Scanner(System.in);

    while (!scan.hasNextInt()){
        scan.next();
        System.out.println(errorText);
    }


    return scan.nextInt();
} 

And after ctrl+d i get NoSuchElementException

Then i try to section try-catch

static public int getInt(String errorText){
    Scanner scan = new Scanner(System.in);

    while (!scan.hasNextInt() ){
        try{
            scan.next();

        }catch(NoSuchElementException e){
            System.out.println("Prechwyciłem!");
        }
        System.out.println(errorText);
    }

    return scan.nextInt();
}

and after that i get infinity loop

0 个答案:

没有答案
相关问题