【问题标题】:try catch not working Java尝试捕获不起作用的 Java
【发布时间】:2018-02-03 23:40:16
【问题描述】:

我正在尝试在 JAVA 中的 while 循环中使用 try-catch 语句,只是为了在将字符串输入提供给 nextInt 时捕获异常,我不知道为什么它在第一次错误输入后继续引发异常。

代码

import java.util.Arrays;
import java.util.Scanner;
public class People{
        public static void main(String[] args){
                Scanner in=new Scanner(System.in);
                Scanner inS=new Scanner(System.in);
                int i=0;
                System.out.println("Enter number of people");
                int n=in.nextInt();
                int[] age=new int[n];
                String[] name=new String[n];
                double[] aIncome=new double[n];
                while (i<n){
                        try{

                                System.out.println(i+"Enter your last and first name (for e.g. if full name is \"Rahul Gupta\" then enter \"Gupta Rahul\") : ");
                                name[i]=inS.nextLine();
                                System.out.println("Now putting name");
                                System.out.println("Enter your age: ");
                                age[i]=in.nextInt();
                                System.out.println("Now putting age");
                                System.out.println("Enter your annual income: ");
                                aIncome[i]=in.nextDouble();
                                System.out.println("Now putting income");
                                i++;
                        }
                        catch(Exception InputMismatchException){
                                System.out.println("Error !! Wrong input, Please try again.");

                        }
                }
                System.out.println(Arrays.toString(age));
                System.out.println(Arrays.toString(name));
                System.out.println(Arrays.toString(aIncome));
        }
}

当输入正确时。

Script started on Sat 03 Feb 2018 07:55:42 PM NST
amehla@slbnen3000pc50:~/Desktop/test$ jva KKKava People.K
Enter number of people
3
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
harit Gupta
Now putting name
Enter your age: 
26
Now putting age
Enter your annual income: 
59495
Now putting income
1Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
59
Now putting age
Enter your annual income: 
35695
Now putting income
2Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Shikha kom
Now putting name
Enter your age: 
56
Now putting age
Enter your annual income: 
59565
Now putting income
[26, 59, 56]
[harit Gupta, Rahul Gupta, Shikha kom]
[59495.0, 35695.0, 59565.0]

但是当输入不正确时,这将无限次进行。

amehla@slbnen3000pc50:~/Desktop/test$ java People
Enter number of people
3
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
59
Now putting age
Enter your annual income: 
fasdf
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahul Gupta
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
Rahu lasdf
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
asdf adsf
Now putting name
Enter your age: 
Error !! Wrong input, Please try again.
0Enter your last and first name (for e.g. if full name is "Rahul Gupta" then enter "Gupta Rahul") : 
^Camehla@slbnen3000pc50:~/Desktop/test$ exit
exit

Script done on Sat 03 Feb 2018 07:57:22 PM NST

会很有帮助,即使有人回复。

谢谢。

【问题讨论】:

标签: java exception while-loop try-catch


【解决方案1】:

当您混合搭配 nextLine()nextInt()nextDouble() 或其中任何一个时,换行符会发生一些奇怪的事情。如果您将代码中对nextInt()nextDouble() 的调用替换为Integer.valueOf(inS.nextLine())Double.valueOf(inS.nextLine()),那么应该可以解决您的问题。

作为一般规则,如果您在命令行读取任何用户输入,您应该读取整行并解析整行。不要尝试获取单个令牌,它会变得非常混乱。

【讨论】:

    【解决方案2】:

    我尝试运行您的代码,发现三个可以解决您的问题的更改。

    首先 - 您不需要两个扫描仪。只用一个。完全摆脱in2

    下一步 - 摆脱 in2 有点搞砸了 name[i]=inS.nextLine(); 您可以通过将其更改为以下内容来修复它:name[i]=in.next(); 我不确定为什么这可以解决问题,但这是我的最佳猜测(其他用户,如果您对此了解更多,请说出来!):

    当您使用nextLine() 时,扫描程序会查找下一个\n 字符之前的所有内容。在之前在int n=in.nextInt(); 行中对扫描仪的调用中,扫描仪仅读取数字本身,而不是用户在输入数字时输入的相应\n 换行符。因此,调用in.nextLine() 将导致扫描程序再次读取本应作为名称的相同值。我们不希望这样 - 我们只想读取用户输入的下一个 tokennext() 做得很好。

    最后 - 我还将 catch(Exception InputMismatchException){... 行更改为更传统的 catch 语句编写方式:catch(InputMismatchException e){...

    【讨论】:

      【解决方案3】:

      当您输入输入值时,您可以通过按Enter 键来接受它。它在输入的值之后生成换行符。在您调用nextLine() 方法的某些下一行代码中,它会读取剩余的换行符而不是您键入的输入。要在调用nextInt()nextDouble() 后清除换行符,请将nextLine() 放在这些方法之后。

      另一种可能性是调用Integer.parseInt(in.nextLine())Double.parseDouble(in.nextLine()) 之类的方法,因为它们会自动删除剩余的换行符。

      您还应该考虑将in.nextLine() 方法放在catch 块中,以在输入引发异常时摆脱剩余的换行符:

      您的代码中存在的另一个问题是这部分:

      catch(Exception InputMismatchException) {...}
      

      使用该代码,您可以捕获 ANY 类型的 Exception - 不仅是 InputMismatchException,还有任何其他继承自 Exception 类和 Exception 本身的类型 - 括号中的第一个是类Exception 你想捕捉,然后你想在 catch 块中调用它的名称 - 将其更改为:

      catch(InputMismatchException ex ) {...}
      

      这样你只会捕获InputMismatchException.

      【讨论】:

        【解决方案4】:

        我不太明白这个问题,但我猜你想要的是在抛出第一个异常后退出循环?然后而不是拥有

        while (...) {
            try {
                ...
            } catch (...) {
                ...
            }
        }
        

        你可以写

        try {
            while (...) {
                ...
            }
        } catch (...) {
            ...
        }
        

        或者只是在你的 catch 块中添加一个 break 语句来退出周围的 while 循环。

        【讨论】:

          猜你喜欢
          • 2018-05-31
          • 1970-01-01
          • 2012-01-28
          • 2017-09-12
          • 1970-01-01
          • 2018-03-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多