java:输入两个错误值后程序崩溃

e4eetjau  于 2021-06-30  发布在  Java
关注(0)|答案(4)|浏览(256)

我编写了一个程序,计算gcd(最大公因数)和lcm(最小公倍数)。一切正常,除了 try {...} catch(...) {...} . 以下是代码中无法正常工作的部分:

try {
    num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
    System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
    System.out.print("Enter your first number: ");
    num1 = Integer.parseInt(sc.nextLine());
}

当我输入例如字母时,它会说:

Your input is not an integer (number w/o decimals)! Try again.
Enter your first number:

但当我第二次输入字母时,程序崩溃了:

Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:658)
    at java.base/java.lang.Integer.parseInt(Integer.java:776)
    at GCDLCMgetter.main(GCDLCMgetter.java:56)

这可能是我犯的一个很简单的错误,但我想不出来。。。
谢谢您

wydwbb8l

wydwbb8l1#

因为你的第二个提示在catch块里面。与其在catch块中再次提示,不如将整个代码段 Package 在一个循环中,以便它返回try块再次提示。比如:

boolean repeat = true;
while(repeat){
    try{
        //Prompt for input
        repeat = false;
    }catch(Exception e) {
        //Display error message
    }
}
carvr3hs

carvr3hs2#

第二个parseint方法调用不在try-catch块中。这种逻辑需要使用循环。

koaltpgm

koaltpgm3#

在您的代码中,它会执行两次:
读一行在 try{...} 有一个 Exception 异常由 catch(Exception e){...} 这个 num1 = Integer.parseInt(sc.nextLine()); 内部 catch(Exception e){...} 无法处理。它没有放在里面 try{} .
执行已完成,因为最后一个异常无法由任何 catch .
看来你用的是扫描器,我建议你用循环的方式:

while (sc.hasNextLine()){
    try {
        System.out.print("Enter your first number: ");
        num1 = Integer.parseInt(sc.nextLine());
    }
    catch(Exception e) {
        System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
    }
}

如果您正在管理整数,那么使用scanner.nextint()会很有趣

while (sc.hasNextInt()){
    try {
        System.out.print("Enter your first number: ");
        num1 = sc.nextInt());
    }
    catch(Exception e) {
        System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
    }
}
qrjkbowd

qrjkbowd4#

当你第一次写信的时候,它就进入了 catch 阻止。显示错误消息。然后执行行 num1 = Integer.parseInt(sc.nextLine()); 再次输入字母,但这次没有 try-catch 阻止来处理这个。所以它抛出了错误。

相关问题