输入错误类型时,如何防止扫描仪抛出异常? [英] How do I keep a Scanner from throwing exceptions when the wrong type is entered?

查看:33
本文介绍了输入错误类型时,如何防止扫描仪抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些示例代码:

import java.util.Scanner;
class In
{
    public static void main (String[]arg) 
    {
    Scanner in = new Scanner (System.in) ;
    System.out.println ("how many are invading?") ;
    int a = in.nextInt() ; 
    System.out.println (a) ; 
    } 
}

如果我运行程序并给它一个 int4,那么一切都会好起来的.

If I run the program and give it an int like 4, then everything goes fine.

另一方面,如果我回答太多,它不会嘲笑我的笑话.相反,我得到了这个(如预期的那样):

On the other hand, if I answer too many it doesn't laugh at my funny joke. Instead I get this(as expected):

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:819)
    at java.util.Scanner.next(Scanner.java:1431)
    at java.util.Scanner.nextInt(Scanner.java:2040)
    at java.util.Scanner.nextInt(Scanner.java:2000)
    at In.main(In.java:9)

有没有办法让它忽略不是整数的条目或重新提示有多少人正在入侵?"我想知道如何做到这两点.

Is there a way to make it ignore entries that aren't ints or re prompt with "How many are invading?" I'd like to know how to do both of these.

推荐答案

您可以使用 Scanner 具有的众多 hasNext* 方法之一进行预验证.

You can use one of the many hasNext* methods that Scanner has for pre-validation.

    if (in.hasNextInt()) {
        int a = in.nextInt() ; 
        System.out.println(a);
    } else {
        System.out.println("Sorry, couldn't understand you!");
    }

这甚至可以防止 InputMismatchException 被抛出,因为在你阅读它之前你总是确保它WILL匹配.

This prevents InputMismatchException from even being thrown, because you always make sure that it WILL match before you read it.

  • boolean hasNextInt():如果此扫描器输入中的下一个标记可以使用 true>nextInt() 方法.扫描仪未通过任何输入.

  • boolean hasNextInt(): Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

String nextLine():将此扫描器推进到当前行并返回被跳过的输入.

String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

请记住以粗体显示的部分.hasNextInt() 不会超过任何输入.如果它返回true,您可以通过调用nextInt() 来推进扫描器,这不会抛出InputMismatchException.

Do keep in mind the sections in bold. hasNextInt() doesn't advance past any input. If it returns true, you can advance the scanner by calling nextInt(), which will not throw an InputMismatchException.

如果它返回false,那么您需要跳过垃圾".最简单的方法是调用 nextLine(),可能两次,但至少一次.

If it returns false, then you need to skip past the "garbage". The easiest way to do this is just by calling nextLine(), probably twice but at least once.

您可能需要执行两次 nextLine() 的原因如下:假设这是输入的内容:

Why you may need to do nextLine() twice is the following: suppose this is the input entered:

42[enter]
too many![enter]
0[enter]

假设扫描仪位于该输入的开头.

Let's say the scanner is at the beginning of that input.

  • hasNextInt() 为真,nextInt() 返回42;扫描仪现在位于就在第一个 [enter] 之前.
  • hasNextInt() 为假,nextLine() 返回空字符串,第二个 nextLine() 也返回 "很多!";扫描仪现在位于 就在第二个 [enter] 之后.
  • hasNextInt() 为真,nextInt() 返回 0;扫描仪现在位于就在第三个 [enter] 之前.
  • hasNextInt() is true, nextInt() returns 42; scanner is now at just before the first [enter].
  • hasNextInt() is false, nextLine() returns an empty string, a second nextLine() returns "too many!"; scanner is now at just after the second [enter].
  • hasNextInt() is true, nextInt() returns 0; scanner is now at just before the third [enter].

以下是将其中一些内容组合在一起的示例.您可以尝试使用它来研究 Scanner 的工作原理.

Here's an example of putting some of these things together. You can experiment with it to study how Scanner works.

        Scanner in = new Scanner (System.in) ;
        System.out.println("Age?");
        while (!in.hasNextInt()) {
            in.next(); // What happens if you use nextLine() instead?
        }
        int age = in.nextInt();
        in.nextLine(); // What happens if you remove this statement?
        
        System.out.println("Name?");
        String name = in.nextLine();
        
        System.out.format("[%s] is %d years old", name, age);

假设输入是:

He is probably close to 100 now...[enter]
Elvis, of course[enter]

那么输出的最后一行是:

Then the last line of the output is:

[Elvis, of course] is 100 years old

这篇关于输入错误类型时,如何防止扫描仪抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆