Java try-catch递归中的NumberFormatException不';2次或2次以上后不工作“;“错误”;
因此,我试图编写一个方法,检查扫描仪输入是否为Java try-catch递归中的NumberFormatException不';2次或2次以上后不工作“;“错误”;,java,recursion,try-catch,numberformatexception,Java,Recursion,Try Catch,Numberformatexception,因此,我试图编写一个方法,检查扫描仪输入是否为int,并循环错误消息,直到用户输入int。只要苏联没有给出超过1个错误输入,下面的方法就有效。如果我输入多个字母,然后输入一个int,程序就会崩溃。我认为这可能与我的try-catch只捕获1个异常有关,但不确定,而且似乎无法使它工作。有人知道我怎么解决这个问题吗 调用方法: System.out.println("Write the street number of the sender: "); int senderStreetNumber =
int
,并循环错误消息,直到用户输入int
。只要苏联没有给出超过1个错误输入,下面的方法就有效。如果我输入多个字母,然后输入一个int,程序就会崩溃。我认为这可能与我的try-catch只捕获1个异常有关,但不确定,而且似乎无法使它工作。有人知道我怎么解决这个问题吗
调用方法:
System.out.println("Write the street number of the sender: ");
int senderStreetNumber = checkInt(sc.nextLine);
方法:
public static int checkInt (String value){
Scanner sc = new Scanner(System.in);
try{
Integer.parseInt(value);
} catch(NumberFormatException nfe) {
System.out.println("ERROR! Please enter a number.");
value = sc.nextLine();
checkInt(value);
}
int convertedValue = Integer.parseInt(value);
return convertedValue;
}
你的递归逻辑不好 让我试着解释一下你的错误 第一次进入函数时,您“检查值是否为int) 如果不是你的话,那就去疗养吧。 让我们说第二次是好的。 然后,您将cto转换为值 然后,恢复工作开始了,你回到了你第一次进监狱的时候。
然后它再次执行转换后的值,而您没有捕捉到该异常,因此您的应用程序会崩溃,类似这样的情况。没有在IDE中编码,只是从大脑到键盘。 希望有帮助,帕特里克
Scanner sc = new Scanner(System.in);
int senderStreetNumber;
boolean ok = false;
while(!ok) {
System.out.println("Write the street number of the sender: ");
try {
senderStreetNumber = Integer.parseInt(sc.nextLine());
ok = true;
} catch (NumberFormatException nfe) {
System.out.println("ERROR! Please enter a number.");
}
}
你使用递归并忽略嵌套调用的结果的原因是什么?我必须承认我对编码非常陌生,不确定我会怎么做。啊,我明白了。是的,我可以告诉你我没有正确使用它,谢谢你的提醒。有没有什么方法可以正确地使用它来满足我的需要,或者你建议我使用一个diff完全不同的方法?我会做一个while循环或一个do-while,直到你得到一个好的值,然后返回该值。谢谢你的帮助。我想我误解了递归的用途,我会尝试重写实际运行良好的方法!非常感谢你的帮助
This works.., just modified your program..tested
public static int checkInt(String value) {
Scanner sc = new Scanner(System.in);
try {
return Integer.parseInt(value);
}catch (Exception e) {
System.out.println("Error please enter correct..");
value = sc.nextLine();
return checkInt(value);
}
//int convertedValue = Integer.parseInt(value);
//return convertedValue;
}