所以,我搜索了谷歌和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;
}
}
}
答案 0 :(得分:3)
int a = keyboard.nextInt();
抛出了异常,它位于try catch块之外。
将调用放在try块中的int a = keyboard.nextInt();
。
您的代码还有其他问题:
verifyAge()
会返回一个从未使用过的boolean
。
你的getAge()
方法是递归的,假设用户输入一个数字,它就会循环 - 这是你想要的吗?
<强>更新强>
public static int getAge(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = -1;
while(!verifyAge(age)){ // will loop until there's a valid age
try{
age = scanner.nextInt();
catch (InputMismatchException e){
System.out.println("You may only enter integers as an age. Try again.");
}
}
return age; // your current code doesn't do anything with this return value
}
public static boolean verifyAge (int a){ // would be better named isValidAge()
if (a >= 0 && a <= 122){
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}else{ // no need to call getAge() here
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
return false;
}
}
答案 1 :(得分:2)
代码不在try
块
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
所以它不会被抓住。
答案 2 :(得分:1)
查看实际抛出异常的代码行。如果它不在try/catch
块中,则不会被捕获。
请改为尝试:
try
{
int a = keyboard.nextInt();
verifyAge(a);
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}