0

I'm trying to make sure that the users input is an integer but when I use the below code I just get an infinite loop of the print statement. Any advice of how to improve?

boolean valid = false;
System.out.println("What block are you gathering? (use minecraft block ids)");
while(valid == false){
    try{
        block = input.nextInt();
        valid = true;
    }
    catch(InputMismatchException exception){
        System.out.println("What block are you gathering? (use minecraft block ids)");
        valid = false;
    }
}
Aleksandar
  • 1,163
  • 22
  • 41
deano3663
  • 1
  • 3
  • What type is `block`? – Uma Kanth Jul 05 '15 at 16:54
  • @UmaKanth Doesn't matter here :). – Tom Jul 05 '15 at 16:55
  • Could you elaborate a little more? ive used NumberFormatException but get this error instead : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at firsttry.Main.main(Main.java:28) – deano3663 Jul 05 '15 at 16:55
  • 2
    Also it's always better practice to write `while(!valid)` rather than `while(valid == false)` – tankucukoglu Jul 05 '15 at 16:55
  • @Tom Nice find! That's exactly the problem. – Seelenvirtuose Jul 05 '15 at 16:57
  • what is input in your code block? – Ravindra babu Jul 05 '15 at 16:57
  • @Seelenvirtuose Well, it is like "why is nextLine() skipped after nextInt()" ... these questions were asked and answered hundreds of times before :D. Just needed to find one of them. – Tom Jul 05 '15 at 17:01
  • Sorry about asking a duplicate question i did try and find an answer but guess i didn't look hard enough. thanks for the help everyone – deano3663 Jul 05 '15 at 17:07

1 Answers1

2

nextInt() doesn't consume invalid input so it will try read same invalid value over and over again. To solve this problem you need to consume it explicitly by calling next() or nextLine() which accept any value.

BTW to make your code cleaner and avoid expensive operations like creating exceptions you should use methods like hasNextInt() .

Here is how you can organize your code

System.out.println("What block are you gathering? (use minecraft block ids)");
while(!input.hasNextInt()){
    input.nextLine();// consume invalid values until end of line, 
                     // use next() if you want to consume them one by one.
    System.out.println("That is not integer. Please try again");
}
//here we are sure that next element will be int, so lets read it
block = input.nextInt();
Pshemo
  • 122,468
  • 25
  • 185
  • 269