[英]How to use hasNextInt in Java to check if the entered value is integer or not?
I am trying to make a program that asks the user to enter age and loop until the age is positive or a number.我正在尝试制作一个程序,要求用户输入年龄并循环,直到年龄为正数或数字。 When I enter negative number, the look works and it asks to enter the number again but when I enter letters like "xyz" instead, the loop doesn't work and and the program crashes.
当我输入负数时,外观有效并且它要求再次输入数字但是当我输入像“xyz”这样的字母时,循环不起作用并且程序崩溃。
public static void firstScannerMethod () {
Scanner scanner = new Scanner(System.in); //importing scanner class
System.out.println("enter your age: ");
boolean hasNextIntAge = scanner.hasNextInt(); //checking to see if next entered value is an integer
int myAge = scanner.nextInt();
scanner.nextLine(); //handling enter
while (myAge < 0 || !hasNextIntAge) { // if age is less than 0 or if age is not an integer, prompt again
System.out.println("invalid age, try again");
System.out.println("enter your age: ");
myAge = scanner.nextInt();
scanner.nextLine();
}
System.out.println("your age is " + myAge);
scanner.close();
}
You are not checking the value of hasNextIntAge before calling the nextInt method.在调用 nextInt 方法之前,您没有检查 hasNextIntAge 的值。 As a result, when nextInt gets a string value it throws an InputMismatchException.
因此,当 nextInt 获取字符串值时,它会抛出 InputMismatchException。 I have updated your code to set myAge only if the input is an integer.
我已更新您的代码以仅在输入为 integer 时设置 myAge。
public static void firstScannerMethod () {
Scanner scanner = new Scanner(System.in);
System.out.println("enter your age: ");
while (!scanner.hasNextInt()) {
System.out.println("invalid age, try again");
scanner.next();
}
int myAge = scanner.nextInt();
while (myAge < 0) {
System.out.println("invalid age, try again");
while (!scanner.hasNextInt()) {
System.out.println("invalid age, try again");
scanner.next();
}
myAge = scanner.nextInt();
}
System.out.println("your age is " + myAge);
scanner.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.