Redoing a try after catch in Java

眉间皱痕 提交于 2019-12-22 13:47:20

问题


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.


回答1:


The documentation for java.util.Scanner states

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.

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




回答2:


As well as Jeff's answer, there's no indication that anything will ever set condition back to true after it's been set to false once. You could make it a local variable, or you could just return from the try block:

public int intInput(String text)    
{
    do
    {
        System.out.print(text);
        try
        {
            return scanner.nextInt();
        }
        catch (java.util.InputMismatchException error)
        {
            System.out.println("Please use valid input.");
            // Consume input here, appropriately...
        }
    } while (true);
}

Now the method doesn't affect any state other than the scanner, which is probably what you want - and (IMO) it's simpler as well.



来源:https://stackoverflow.com/questions/7529113/redoing-a-try-after-catch-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!