0
public void processing()
{

    System.out.println("Please enter the amount of saving per month: ");

    try
    {
        while(input.hasNext())
        {
            setSavingPermonth(input.nextDouble());

            System.out.println("Please enter expected interest rate: ");
            setInterestRate(input.nextDouble());

            System.out.println("Please enter number of month for saving: ");
            setNumberOfMonth(input.nextInt());

            displayInputs();
            System.out.println();
            totalContibution();
            totalSavingAmount();

            System.out.println();
            System.out.println("\nPlease enter the amount of saving per month: \n(or <Ctrl + D> to close the program)");
        }
    }
    catch(InputMismatchException inputMismatchException)
    {
        System.err.println("Input must be numeric. \ntry again: ");
              //**Anything need to done here in order to go back to setInterestRate()?**
    }
}

我想回到异常捕获错误输入异常之前的位置,例如,我为 setInterestRate() 输入了一个字符串,但 Java 将我捕获到那里,并显示错误消息,问题:我该如何返回到那里以便我可以重新输入正确的数据?

4

2 回答 2

3

重写您的代码,使其使用以下方法:

static double inputDouble(Scanner input) {
  while (input.hasNext()) try {
    return input.nextDouble();
  }
  catch (InputMismatchException e) {
    System.out.println("Wrong input. Try again.");
    input.next(); // consume the invalid double
  }
  throw new IOException("Input stream closed");
}
于 2013-01-20T16:10:49.480 回答
1

您可以使用以下两种方法来获取整数和双精度:

static int getIntInput(Scanner input) {
    while(true)
    {
        try {
            if (input.hasNext()) {
                return input.nextInt();
            }
        } catch (InputMismatchException  e) {
            System.err.println("Input must be numeric. \ntry again: ");
            input.next();
        }
    }
}

static double getDoubleInput(Scanner input) {
    while(true)
    {
        try {
            if (input.hasNext()) {
                return input.nextDouble();
            }
        } catch (InputMismatchException  e) {
            System.err.println("Input must be numeric. \ntry again: ");
            input.next();
        }
    }
}
于 2013-01-20T16:31:33.840 回答