-1

Is it able for the code bellow to run correctly without creating a new Scanner object inside the loop?

Can it be done with just a definition of a Scanner object outside the loop(commented code)?

// Scanner sc = new Scanner(System.in);
while(true){
   Scanner sc = new Scanner(System.in);
  try{
    int x = sc.nextInt();
    System.out.printf("You gave %d\n", x);
  }catch(Exception e){
    System.out.println("Plz give a valid number!");
  }finally{
    sc.close();
  }
}
Mr T
  • 506
  • 2
  • 9
  • 26
  • do you want once you get Valid Number then no more asking ? i mean once Valid value getting then want to free from while loop ? – Vishal Gajera Jun 01 '16 at 14:47
  • About closing the Scanner: [java.util.NoSuchElementException - Scanner reading user input](http://stackoverflow.com/q/13042008) – Tom Jun 01 '16 at 15:09
  • @vishalgajera No, I just want to give a number, then tell me the number and when the loop starts give new input again! – Mr T Jun 01 '16 at 15:10

1 Answers1

1

When you define the Scanner outside of the loop, you are using the same scanner on each run of the loop. If the next token is not a valid integer, sc.nextInt() will fail and the scanner will not advance beyond that token. On the next iteration, sc.nextInt() will see the same invalid token and will fail again. Similarly, if you close the scanner, the next iteration of the loop will call sc.nextInt() on the closed scanner, which will fail. Subsequent iterations will fail for the same reason.

On the other hand, when the scanner is defined within the loop, each iteration uses a new scanner. Even if sc.nextInt() fails, the next iteration will use a fresh scanner that doesn't contain the same invalid token.

Reinstate Monica
  • 2,420
  • 14
  • 23
  • So the only solution is to create a new Scanner all the time? And close it of course? But doesn't that takes a lot of resources, CPU and so on? :( – Mr T Jun 01 '16 at 15:11
  • @Skemelio No there are other ways to solve this, just read the duplicate question (see the link above your question). – Tom Jun 01 '16 at 15:16