[英]How to go back to a particular point from a caught exception in java
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捕获了我,并显示错误消息,问题:我该如何返回到那里,以便我可以重新输入正确的数据?
重写您的代码,使其使用以下方法:
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");
}
您可以使用以下两种方法来获取整数和双精度:
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.