所以,我在google和stackoverflow上搜索了一些,但我似乎找不到这个问题的答案。
我有两种方法。第一种方法 getAge 只是从用户那里获取一个整数作为输入。然后它意味着将该输入传递给 verifyAge,以确保它在正确的范围内。
然而; 如果他们应该输入任何不是整数的东西,它应该显示一条消息并再次调用 getAge 以重新启动输入过程。我有一个 try-catch 设置,但它仍然可以回到 JVM。根据另一篇文章的回答;我在做什么是正确的。但它似乎仍然没有工作。所以这是我现在尝试运行它时遇到的错误:
Please enter your age: notint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Ch2ProgLabWilson.getAge(Ch2ProgLabWilson.java:22)
at Ch2ProgLabWilson.main(Ch2ProgLabWilson.java:15)
我写的是:
import java.util.* ;
import java.util.Scanner;
public class Ch2ProgLabWilson {
public static void main(String[] args) {
getAge();
}
public static int getAge()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
getAge();
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}
return a;
}
//
public static boolean verifyAge (int a)
{
if (a >= 0 && a <= 122)
{
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}
else
{
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
getAge();
return false;
}
}
}