问题
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;
}
回答1:
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);
回答2:
You do not need an additional check. The exception is just there so you can act accordingly in your program. After all, it doesn't really matter how exactly the input was wrong. Just catch the exception (NumberFormatException, I guess?) and upon catching it, print an error message:
while (true) try {
// here goes your code that pretends only valid inputs can occur
break; // or better yet, put this in a method and return
} catch (NumberFormatException nfex) { // or whatever is appropriate
System.err.println("You're supposed to enter integral values.");
// will repeat due to while above
}
回答3:
public class SomeClass {
public static void main(String args[]) {
double x = 150.999; // 1
/* int x = (int) 150.999; */ // 2
if ( x >= 10 && x <= 150 ) { // The comparison will still work
System.out.print("x between 10 and 150: " + x + "\n");
}
}
}
- Declare x as double, comparisons between double and int will still work.
- Or, cast the number and any decimal values will be discarded.
来源:https://stackoverflow.com/questions/19816013/java-how-to-test-if-an-input-is-a-double-or-an-int