这是一些示例代码:

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) ; 
    } 
}

如果我运行该程序并给它一个 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)

是否有一种方法可以使其忽略没有INT或提示的条目“有多少人入侵?”我想知道如何做这两个。

有帮助吗?

解决方案

您可以使用众多 hasNext* 方法 Scanner 具有预验证。

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

这可以防止 InputMismatchException 甚至被扔了,因为您总是确保 将要 在阅读之前匹配。


java.util.Scanner API

  • boolean hasNextInt(): :返回 true 如果此扫描仪输入中的下一个令牌可以将其解释为默认radix中的int值 nextInt() 方法。 扫描仪不会超越任何输入。

  • String nextLine(): 超越当前线路的扫描仪 并返回跳过的输入。

请记住,该部分大胆。 hasNextInt() 不会超越任何输入。如果返回 true, ,您可以通过打电话来推进扫描仪 nextInt(), ,不会扔 InputMismatchException.

如果返回 false, ,然后您需要跳过“垃圾”。最简单的方法就是打电话 nextLine(), ,大概两次,但至少一次。

为什么您可能需要做 nextLine() 两次是:假设这是输入的:

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

假设扫描仪正处于该输入的开始。

  • hasNextInt() 是真的, nextInt() 返回 42;扫描仪现在在 就在 首先 [enter].
  • hasNextInt() 是错误的, 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);

假设输入是:

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

那么输出的最后一行是:

[Elvis, of course] is 100 years old

其他提示

总的来说,我真的非常非常不喜欢使用相同的库来阅读和解析。语言库似乎非常僵化,通常不能屈服于您的意志。

从System.in中提取数据的第一步不应失败,因此请将其读成一个字符串中,然后将该字符串变量转换为int。如果转换失败,很棒 - 打印出您的错误并继续。

当您用可以抛出异常的东西包裹流时,它会使整个混乱的潮流散发出来的混淆。

这始终是一个好处 当发生错误与方法相反时,您的申请会引发错误 保持 从发生。

一种选择是将代码包装在 try {...} catch {...}InputMismatchException。您可能还想将代码包装在 while 循环有 Scanner 继续提示直到满足特定条件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top