4

In the catch block, I'm trying to correct for user bad-input issues. When testing it, if I use the "break" keyword, it doesn't jump to the initial question. If I use "continue", it loops infinitely. "Sc.next();" doesn't seem to resolve it either.

Here's the relevant part of the code.

public class ComputerAge {
    private static int age;
    private static int year;
    private static int month;
    private static int date;
    private static Calendar birthdate;

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Enter the numeral representing your birth month: ");
        do {
            try {
                month = sc.nextInt();
            } catch (InputMismatchException ime){
                System.out.println("Your respone must be a whole number");
                break;
            }
        } while (!sc.hasNextInt());
4

5 回答 5

3

为了解决问题,我们应该最终确定我们想要完成的事情。
我们希望月份是一个数字月份,即 number > 0。

因此:

  • 如果用户填写正确的数字month,将被填写。
  • 否则,将抛出异常month并将保持为“0”。

结论:我们希望我们的程序在月份等于 0 时继续运行。

解决方案非常简单:

虽然条件应该是:

while (month == 0);

你应该break改为sc.next().

于 2014-03-08T22:28:17.523 回答
3

您的方法的问题是,当您调用sc.nextInt()引发异常时,Scanner不会提前其读取位置。您需要通过在块内调用而不是调用来推进读取指针:sc.next()catchbreak

do {
    try {
        month = sc.nextInt();
    } catch (InputMismatchException ime){
        System.out.println("Your respone must be a whole number");
        sc.next(); // This will advance the reading position
    }
} while (!sc.hasNextInt());
于 2014-03-08T22:24:20.900 回答
2

首先,您必须避免在迭代语句中使用 try/catch 以提高性能。

您可以重新编码以使中断以这种方式工作(请记住,de do-while 将至少执行一次,因此如果您的扫描仪检索空值,您将拥有 nullPointer)

    try {
       while (sc != null && !sc.hasNextInt()) {
            month = sc.nextInt();
        } 
    } catch (InputMismatchException ime){
            System.out.println("Your respone must be a whole number");
    }
于 2014-03-08T22:27:15.030 回答
2

我认为您应该使用无限循环,并且当输入正确(没有抛出异常)时,使用break来完成循环:

public static void main(String args[])
{
    System.out.print("Enter the numeral representing your birth month: ");
    do {
        try {
            int month = sc.nextInt();
            break;
        } catch (InputMismatchException ime) {
            System.out.println("Your respone must be a whole number");
            sc.nextLine();
        }
    } while (true);
}

此外,您必须sc.nextLine()catch块中使用,因为当您输入一些输入并按 时Enter,会添加一个换行符,并且nextInt()不会读取它。你必须使用nextLine()来消耗那个字符。有关此问题的更多信息,您可以阅读此内容

于 2014-03-08T22:24:29.460 回答
1

确保您可以先获取整数,然后使用正则表达式。如果可能,不要使用异常来强制执行代码逻辑。

int month;
boolean correct = false;
while (!correct && sc.hasNextLine())
{
    String line = sc.nextLine();
    if (!line.matches("^[0-9]+$"))
    {
        System.out.println("Your response must be a whole number");
        correct = false;
    }
    else
    {
        month = Integer.parseInt(line);
        correct = true;
    }
}
于 2014-03-08T22:35:45.040 回答