当发生异常时,我希望将用户返回到发生异常的代码行,而不是让他们再次输入所有内容。有没有一种简单/简单的方法可以做到这一点?
Scanner input = new Scanner(System.in);
double initialAmount = 0.0;
String type = "";
double interestRate = 0.0;
boolean finished = false;
try{
System.out.print("\nInitial Amount: ");
input = new Scanner(System.in);
initialAmount = input.nextDouble();
System.out.print("Compound/Simple: ");
input = new Scanner(System.in);
type = input.nextLine();
if (!type.equalsIgnoreCase("compound") && !type.equalsIgnoreCase("simple")){
System.out.println(type);
throw new IllegalArgumentException();
}
System.out.print("Interest Rate: ");
input = new Scanner(System.in);
interestRate = input.nextDouble();
finished = true;
}
catch(Exception e) {
System.out.print("\n----- Please check that you have entered a corrrect value! -----\n");
createUserInvestment();
}
Investment invest = new Investment(interestRate, initialAmount, type);
return invest;
最佳答案
没有必要在代码中抛出任何异常。唯一需要 try/catch 的代码是 nextDouble() 赋值。这可能会导致错误,因为输入并不总是 double ,但分配字符串要容易得多,并且不需要被捕获。要返回到该行,请将要在 while 循环中重复的行括起来。在循环内,使用 if 语句检查输入。当获得所需的输入时,使用break关键字结束循环。这将继续分配变量,直到它被分配到您想要的位置。 警惕不必要地使用异常。异常是对象,因此内存消耗更大。因此,仅当无法用程序逻辑处理错误时才使用异常。我并不是说你不应该使用异常,只是说你应该只在 if 语句无法处理错误的情况下使用它们。
关于java - 将用户返回到发生异常的代码行 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732116/