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

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

问题描述

以下是一些示例代码:

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 ,然后一切顺利。

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.

推荐答案

您可以使用众多 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 甚至被抛出,因为在你阅读它之前总是确保它匹配。

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


  • boolean hasNextInt():返回 true 如果此扫描器输入中的下一个标记可以使用<$ c解释为默认基数中的int值$ c> 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 ()为false, 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].

以下是将这些内容放在一起的示例。您可以尝试使用它来研究扫描仪的工作原理。

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天全站免登陆