您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

输入错误的类型时,如何防止扫描仪抛出异常?

输入错误的类型时,如何防止扫描仪抛出异常?

你可以使用的诸多一个hasNext*方法Scanner有预验证。

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

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

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

String nextLine():使此扫描仪前进到当前行,并返回跳过的输入。

请记住以粗体显示的部分。hasNextInt()不会超过任何输入。如果返回true,你可以通过调用来推进扫描程序nextInt(),不会抛出异常InputMismatchException

如果返回false,则需要跳过“垃圾”。最简单的方法调用nextLine(),可能两次,但至少一次。

为什么你可能需要做nextLine()两次以下操作:假设这是输入的内容

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

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

        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]

然后输出的最后一行是:

[Elvis, of course] is 100 years old
其他 2022/1/1 18:15:43 有431人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶