在Java中捕获后重做一次尝试

Sax*_*ute 2 java try-catch

import java.util.Scanner;

public class Questioner {   

Scanner scanner = new Scanner(System.in);
boolean condition;
int tempInt;
double tempDouble;

public Questioner()
{
    condition = true;
}

public String stringInput(String text)
{
    System.out.print(text);
    return scanner.nextLine();
}

public int intInput(String text)

{
    do
    {
        System.out.print(text);
        try
        {
            tempInt = scanner.nextInt();
            condition = false;
        }
        catch (java.util.InputMismatchException error)
        {
            System.out.println("Please use valid input.");
        }
    } while (condition == true);

    return tempInt;
}


public double doubleInput(String text)
{
    System.out.print(text);
    try
    {
        return scanner.nextDouble();
    }
    catch (java.util.InputMismatchException error)
    {
        System.out.println("Please use valid input.");
        return 0;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

现在,它在一次错误后无限循环捕获.我怎样才能让它在捕获后回到尝试?boolean condition声明正确,没有编译错误或任何东西.这个代码中的其余代码有点混乱,因为我正在等待重新尝试的答案.

Jef*_*ter 8

文档java.util.Scanner状态

当扫描程序抛出InputMismatchException时,扫描程序将不会传递导致异常的标记,因此可以通过其他方法检索或跳过它.

因此,您将使用此方法无限期地检索.在catch块中,您需要跳过令牌.