Java使用Scanner验证输入

3

我该如何使用InputMismatchException来确定输入到Scanner中的值不是整数?基本上,如果他们输入单词而不是整数,我需要使用InputMismatchException返回一条消息。

while (true) {

        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        try{
            Integer.parseInt(i);
        } catch (InputMismatchException e) {
            System.out.println("Sorry, " + i + " is not a number.");
        }

        if (i == 1) {
            System.out.println("1 was selected");
        } else {
            System.out.println("1 was not selected");

        }

2
错误将由sc.nextInt();这一行抛出,而不是通过执行Integer.parseInt(i);来抛出。因此,将int i = sc.nextInt();放在try catch中处理该异常,就可以解决问题了。 - 3kings
你能否发布你的意思? - user3586248
i have posted below. - 3kings
3个回答

2

请将您的代码更改为以下内容:

while (true) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    try{
       int i = Integer.parseInt(s);

       if (i == 1) {
           System.out.println("1 was selected");
       } else {
           System.out.println("1 was not selected");
       }
    } catch (NumberFormatException e) {
        System.out.println("Sorry, " + s + " is not a number.");
    }


}

更新内容:

  • 注意使用nextLine()。这是因为您似乎希望将输入作为错误消息的一部分,而nextInt()不会让您这样做。
  • 我们现在可以将i声明移动到try块内,以及使用它的代码,这样当输入为"ssss"或其他任何值时,就不会发出"1 未被选中"的消息。
  • 我们使用NumberFormatException,因为这是Integer.parseInt()无法从字符串解析整数时抛出的异常。

那基本上是可以工作的,但在catch部分编译之前会出现错误,指出“i无法解析为变量”。我该如何修复它? - user3586248
@user3586248,你需要在try/catch之外声明它。就在Scanner scan这行的下面。 - 3kings
是的,如果你想在异常的println中使用输入,它需要在try块之外声明...我会更改答案以反映这一点,尽管我通常不会这样做,因为InputMismatchException有一个getMessage()方法可以使用。(你可能不喜欢它给出的消息,所以如果你想要的话,更改它也是可以的)。 - billjamesdev
我尝试了你编辑后的代码,但现在它报错了:“本地变量i可能未被初始化”。 - user3586248
等等...实际上,你不能这样做。我只会在输入为整数时填充。如果你一定要在错误消息中使用输入,你需要使用一个字符串和parseInt。 - billjamesdev

0

这就是我的意思

while (true) {

    Scanner sc = new Scanner(System.in);
    int i = -1;
    try
    {
        i = sc.nextInt();
    } 
    catch (InputMismatchException e)
    {System.out.println("Sorry, " + i + " is not a number.");}

    if (i == 1)
        System.out.println("1 was selected");
    else
        System.out.println("1 was not selected");
}

0

我是编程新手,但我认为我已经得到了你问题的代码。

while (true) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        try{
           int i = Integer.parseInt(s);
           if (i == parseInt(i, 3)) {
               System.out.println(s+" is selected");
           } else {
               System.out.println("Input value is " + s);
           }
        } catch (NumberFormatException e) {
            System.out.println("Sorry, " + s + " is not a number.");
        }}}
        private static int parseInt(int i, int j) {
        // TODO Auto-generated method stub
        return 0;
    }}

参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接