user input check int only
You need to combine the two loops, so that both checks happen every time the end-user enters something new:
for(;;) {
if(!sc.hasNextInt() ) {
System.out.println("only integers!: ");
sc.next(); // discard
continue;
}
choose=sc.nextInt();
if( choose<=0 || choose>30)
{
System.out.print("no, 1-30: ");
continue;
}
break;
}
After the loop exits, choose
is a number between 1
and 30
, inclusive.
BubbleTree
Updated on June 14, 2022Comments
-
BubbleTree almost 2 years
I am trying to have my user input not crash my program by restricting what the user can input such as:
- only being an int
- being between 1-30
The code that I've written works only up to a certain point. If you enter something thats not an int it will check it and ask you to enter again. Then again if you keep typing anything but an int. I have another while loop if it does type an int, and if it's outside the 1-30 zone then it will ask the user to input again. However after that if the user types another "anything but an int" the program will crash. I've tried to combine both the
sc.hasnextint()
and the check for input between 1-30 condition but if i put thesc.nextint()
before thesc.hasnextint()
and the user enters anything but an int, the program crashes. If I put it after the condtion loop, then the userinput will not be declared.int choose; System.out.print("type an integer: "); Scanner sc=new Scanner(System.in); while (!sc.hasNextInt() ) { System.out.println("only integers!: "); sc.next(); // discard } choose=sc.nextInt(); while (choose<=0 || choose>30) { System.out.print("no, 1-30: "); choose=sc.nextInt(); } sc.close();
-
asgs over 11 years+1 for having an always-true
for
loop and having separateif
conditions within it. -
FThompson over 11 yearsBased off of the new information OP has provided in a comment, I'd say that this answer will not fix the issue, because
sc.nextInt()
is failing to parse non-integer inputs. -
Sergey Kalinichenko over 11 years@Vulcan That's OK, because unlike the OP's code this one does not call
nextInt
unlesshasNextInt
returnstrue
. -
FThompson over 11 yearsAh, I didn't notice the second call to
nextInt
in the OP's code, my apologies.