在Java中捕获后重做一次尝试 [英] Redoing a try after catch in Java

查看:153
本文介绍了在Java中捕获后重做一次尝试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    }
}
}

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

Right now, it loops infinitely on the catch after one error. How can I make it go back to the try after a catch? boolean condition is declared properly, no compilation errors or anything. The rest of the code in the class is kind of a mess as I'm waiting for an answer about the re-trying.

推荐答案

java.util的文档 .Scanner states

The documentation for java.util.Scanner states


当扫描程序抛出InputMismatchException时,扫描程序不会传递导致异常的令牌,以便可以通过其他方法检索或跳过它。

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

所以你将无限期地使用这种方法检索。在catch块中,您需要跳过令牌。

So you'll retrieve indefinitely using this method. In the catch block you'll need to skip over the token.

这篇关于在Java中捕获后重做一次尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆