在我的一种方法中,我正在编写一个 try catch 来验证用户的输入。如果用户输入了错误的数据类型,则会再次调用该方法并提示他们重新输入。由于某种原因,当第二次调用该方法时,无论输入的值是什么,它总是返回0。
public static int enterNumGadgets(){
int numOfGadgetsIn = 0;
try{
System.out.println("");
System.out.println("Please enter the number of items you wish to insure.");
numOfGadgetsIn = EasyScanner.nextInt();
}
catch(InputMismatchException exception){
System.out.println("You must enter a number.");
EasyScanner.nextLine(); //consume new line left over
enterNumGadgets(); //call the method again
}
return numOfGadgetsIn;
}
<小时/>
第一次调用该方法时以正确的数据类型输出:
名称:测试
引用号:te123s
小工具数量:1
最贵的商品:1.0
<小时/>第一次调用时输出数据类型不正确,但第二次调用时数据类型正确:
名称:测试
引用编号:te123s
小工具数量:0
最贵的商品:1.0
<小时/>请注意,在第二次调用 EnterNumGadgets() 后,它似乎忽略了在 try{...} 中设置的新值 int numOfGadgetsIn 并将其返回为 0。
任何帮助将不胜感激
最佳答案
第二次 rekursiv 调用(您的用户数据有效)后,您的数据不会分配给新变量。相反,使用第一次调用时的变量(用户数据无效),该变量仍然为 0。
这应该有效:
public static int enterNumGadgets(){
int numOfGadgetsIn = 0;
try{
System.out.println("");
System.out.println("Please enter the number of items you wish to insure.");
numOfGadgetsIn = EasyScanner.nextInt();
}
catch(InputMismatchException exception){
System.out.println("You must enter a number.");
EasyScanner.nextLine(); //consume new line left over
numOfGadgetsIn = enterNumGadgets(); //call the method again
}
return numOfGadgetsIn;
}
关于java - 递归调用后变量值未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931599/