Java 如何使用 Scanner 只接受有效的 int 作为输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2912817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:25:14  来源:igfitidea点击:

How to use Scanner to accept only valid int as input

javavalidationjava.util.scanner

提问by John

I'm trying to make a small program more robust and I need some help with that.

我正在尝试使一个小程序更健壮,我需要一些帮助。

Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;

System.out.print("Enter number 1: ");
num1 = kb.nextInt();

while(num2 < num1) {
    System.out.print("Enter number 2: ");
    num2 = kb.nextInt();
}
  1. Number 2 has to be greater than number 1

  2. Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example rinstead of a number the program just exits.

  1. 数字 2 必须大于数字 1

  2. 我还希望程序自动检查并忽略用户是否输入字符而不是数字。因为现在当用户输入例如r而不是数字时,程序就会退出。

采纳答案by polygenelubricants

Use Scanner.hasNextInt():

使用Scanner.hasNextInt()

Returns trueif the next token in this scanner's input can be interpreted as an intvalue in the default radix using the nextInt()method. The scanner does not advance past any input.

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

Here's a snippet to illustrate:

这是一个片段来说明:

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
    while (!sc.hasNextInt()) sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);

You don't have to parseIntor worry about NumberFormatException. Note that since the hasNextXXXmethods don't advance past any input, you may have to call next()if you want to skip past the "garbage", as shown above.

您不必parseInt担心或担心NumberFormatException。请注意,由于这些hasNextXXX方法不会越过任何输入,next()如果您想跳过“垃圾”,则可能必须调用,如上所示。

Related questions

相关问题

回答by Ledhund

  1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
  2. not knowing what the kb object is, I'd read a Stringand then trying Integer.parseInt()and if you don't catchan exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.
  1. 条件 num2 < num1 应该是 num2 <= num1 如果 num2 必须大于 num1
  2. 不知道 kb 对象是什么,我会读取 aString然后tryingInteger.parseInt()如果你没有catch异常那么它是一个数字,如果你这样做,读取一个新的,也许通过将 num2 设置为 Integer.MIN_VALUE 并使用相同的您的示例中的逻辑类型。

回答by npinti

Try this:

尝试这个:

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("^\d+$");
        Scanner kb = new Scanner(System.in);
        int num1;
        int num2 = 0;
        String temp;
        Matcher numberMatcher;
        System.out.print("Enter number 1: ");
        try
        {
            num1 = kb.nextInt();
        }

        catch (java.util.InputMismatchException e)
        {
            System.out.println("Invalid Input");
            //
            return;
        }
        while(num2<num1)
        {
            System.out.print("Enter number 2: ");
            temp = kb.next();
            numberMatcher = p.matcher(temp);
            if (numberMatcher.matches())
            {
                num2 = Integer.parseInt(temp);
            }

            else
            {
                System.out.println("Invalid Number");
            }
        }
    }

You could try to parse the string into an intas well, but usually people try to avoid throwing exceptions.

您也可以尝试将字符串解析为 an int,但通常人们会尽量避免抛出异常。

What I have done is that I have defined a regular expression that defines a number, \dmeans a numeric digit. The +sign means that there has to be one or more numeric digits. The extra \in front of the \dis because in java, the \is a special character, so it has to be escaped.

我所做的是我定义了一个定义数字的正则表达式,\d表示一个数字。在+有有标志装置是一个或多个数字。\前面的多出来的,\d是因为在java中,\是特殊字符,所以要转义。

回答by aioobe

This should work:

这应该有效:

import java.util.Scanner;

public class Test {
    public static void main(String... args) throws Throwable {
        Scanner kb = new Scanner(System.in);

        int num1;
        System.out.print("Enter number 1: ");
        while (true)
            try {
                num1 = Integer.parseInt(kb.nextLine());
                break;
            } catch (NumberFormatException nfe) {
                System.out.print("Try again: ");
            }

        int num2;
        do {
            System.out.print("Enter number 2: ");
            while (true)
                try {
                    num2 = Integer.parseInt(kb.nextLine());
                    break;
                } catch (NumberFormatException nfe) {
                    System.out.print("Try again: ");
                }
        } while (num2 < num1);

    }
}

回答by Elijah Saounkine

I see that Character.isDigit perfectly suits the need, since the input will be just one symbol. Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:

我看到 Character.isDigit 非常适合需要,因为输入将只是一个符号。当然,我们没有关于这个 kb 对象的任何信息,但以防万一它是一个 java.util.Scanner 实例,我还建议使用 java.io.InputStreamReader 进行命令行输入。下面是一个例子:

java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
  reader.read();
}
catch(Exception e) {
  e.printStackTrace();
}
reader.close();

回答by LB40

What you could do is also to take the next token as a String, converts this string to a char arrayand test that each character in the array is a digit.

您还可以做的是将下一个标记作为字符串,将此字符串转换为 char 数组并测试数组中的每个字符是否为 digit

I think that's correct, if you don't want to deal with the exceptions.

我认为这是正确的,如果你不想处理例外。