如果输入错误的类型,如何防止扫描程序抛出异常?

Dav*_*vid 13 java text-parsing java.util.scanner

这是一些示例代码:

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) ; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

如果我运行该程序并给它一个int喜欢4,那么一切都很顺利.

另一方面,如果我回答too many它并不嘲笑我有趣的笑话.相反,我得到了这个(如预期的那样):

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)
Run Code Online (Sandbox Code Playgroud)

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

pol*_*nts 18

您可以使用许多hasNext*方法中的一种Scanner进行预验证.

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

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


java.util.Scanner API

  • boolean hasNextInt():返回true此扫描器输入中的下一个标记是否可以使用该nextInt()方法解释为默认基数中的int值.扫描仪不会超过任何输入.

  • String nextLine():使此扫描器前进超过当前行并返回跳过的输入.

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

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

为什么您可能需要执行nextLine()两次以下操作:假设这是输入的输入:

42[enter]
too many![enter]
0[enter]
Run Code Online (Sandbox Code Playgroud)

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

  • hasNextInt()是真的,nextInt()回报42; 扫描仪现在就在第一个之前[enter].
  • hasNextInt()是false,nextLine()返回一个空字符串,第二个nextLine()返回"too many!"; 扫描仪现在就在第二个之后[enter].
  • hasNextInt()是真的,nextInt()回报0; 扫描仪现在就在第三个之前[enter].

以下是将这些内容放在一起的示例.你可以试验它来研究它是如何Scanner工作的.

        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);
Run Code Online (Sandbox Code Playgroud)

让我们说输入是:

He is probably close to 100 now...[enter]
Elvis, of course[enter]
Run Code Online (Sandbox Code Playgroud)

然后输出的最后一行是:

[Elvis, of course] is 100 years old
Run Code Online (Sandbox Code Playgroud)