I have a do while loop. Checking x is between two values. Now im supposed to be taking in an int value, but if the user types a double im getting exceptions. How do I incorparate a check in the same if statement so that if the user types a double it would print something like "x must be an int between 10 and 150:"
do {
x = sc.nextInt();
if ( x < 10 || x > 150 ) {
System.out.print("x between 10 and 150: ");
} else {
break;
}
解决方案
You can just catch the exception and handle it, using a while (true) to allow the user to re-try.
Here's my code:
Scanner sc = new Scanner(System.in);
do {
System.out.print("\nInsert a number >>> ");
try {
int x = sc.nextInt();
System.out.println("You inserted " + x);
if (x > 10 && x < 150) {
System.out.print("x between 10 and 150: ");
} else {
break;
}
} catch (InputMismatchException e) {
System.out.println("x must be an int between 10 and 150");
sc.nextLine(); //This line is really important, without it you'll have an endless loop as the sc.nextInt() would be skipped. For more infos, see this answer http://stackoverflow.com/a/8043307/1094430
}
} while (true);