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

发布于 2024-08-26 07:46:05 字数 793 浏览 2 评论 0原文

这是一些示例代码:

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

如果我运行该程序并给它一个像 4 这样的 int ,那么一切都会顺利。

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

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)

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

Here's some sample code:

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笑叹一世浮沉 2024-09-02 07:46:05

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

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

这甚至可以防止抛出InputMismatchException,因为在读取它之前,您始终要确保它匹配。


java.util。扫描仪 API

  • boolean hasNextInt():如果此扫描仪输入中的下一个标记可以解释为 int 值,则返回 true使用 nextInt() 方法的默认基数。 扫描仪不会前进超过任何输入。

  • String nextLine()使扫描仪前进超过当前行并返回输入被跳过。

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

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

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

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

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

  • hasNextInt() 为 true,nextInt() 返回 42;扫描仪现在位于第一个[enter]之前
  • hasNextInt() 为 false,nextLine() 返回空字符串,第二个 nextLine() 返回 “太多!”< /代码>;扫描仪现在位于第二个[enter]之后
  • hasNextInt() 为 true,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

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

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


java.util.Scanner API

  • 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(): Advances this scanner past the current line and returns the input that was skipped.

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.

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.

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

Let's say the input is:

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
很酷不放纵 2024-09-02 07:46:05

总的来说,我真的非常不喜欢使用相同的库调用来进行读取和解析。语言库似乎非常不灵活,而且常常无法按照您的意愿行事。

从 System.in 提取数据的第一步应该不会失败,因此将其作为字符串读取到变量中,然后将该字符串变量转换为 int。如果转换失败,那就太好了——打印您的错误并继续。

当你用可能引发异常的东西包装你的流时,整个混乱让你的流处于什么状态会有点令人困惑。

In general I really, really dislike using the same library call for both reading and parsing. Language libraries seem to be very inflexible and often just can't be bent to your will.

The first step that pulls data from System.in should not be able to fail, so have it read it as a string into a variable, then convert that string variable to an int. If the conversion fails, great--print your error and continue.

When you wrap your stream with something that can throw an exception, it gets kind of confusing just what state the whole mess leaves your stream in.

夜吻♂芭芘 2024-09-02 07:46:05

当错误发生时应用程序抛出错误总是比阻止错误发生的方法更有好处。

一种替代方法是将代码包装在 try {...} catch {...} 块中以处理 InputMismatchException
您可能还希望将代码包装在 while 循环中,以使 Scanner 不断提示,直到满足特定条件。

It's always a benefit to have your application throw an error when an error occurs opposed to ways to keep it from happening.

One alternative is to wrap the code inside a try {...} catch {...} block for InputMismatchException.
You might also want to wrap the code inside a while loop to have the Scanner keep prompting until a specific condition is met.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文