使用Scanner确保用户输入是一个整数[重复]

时间:2021-07-21 21:50:07

This question already has an answer here:

这个问题在这里已有答案:

Desired outcome:

  • Accepts user input
  • 接受用户输入

  • Makes sure user inputs only 1 integer value at a time
  • 确保用户一次只输入1个整数值

  • Stores that integer in a variable
  • 存储变量中的整数

I tried to achieve this by doing the following:

我尝试通过执行以下操作来实现此目的:

  • Store user input in variable
  • 将用户输入存储在变量中

  • Count number of tokens in variable
  • 计算变量中的令牌数

  • If there's not one token, reject the input
  • 如果没有一个令牌,请拒绝输入

  • If the input is not of data type int, reject the input
  • 如果输入不是数据类型int,则拒绝输入

Code:

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter an integer:");
    String myString = scan.nextLine();
    int tokens = new StringTokenizer(myString, " ").countTokens();

    while (tokens != 1 && !scan.hasNextInt()) {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        tokens = new StringTokenizer(myString, " ").countTokens();
    }

    int number = scanner.nextInt();
    System.out.println(number);

This code is full of holes. The output is inconsistent and undesired. It typically ends by throwing a java.util.InputMismatchException error, indicating the value it's trying to store isn't an int. I've experienced this error occur after one loop and after multiple loops, even with the same type and quantity of input (e.g. 2 strings).

这段代码充满了漏洞。输出不一致且不合需要。它通常以抛出java.util.InputMismatchException错误结束,指示它尝试存储的值不是int。我经历过这个错误发生在一个循环之后和多个循环之后,即使输入的类型和数量相同(例如2个字符串)。

Should I keep going with this code, or should I try to approach this problem from a different angle?

我应该继续使用此代码,还是应该尝试从不同角度解决此问题?

1 个解决方案

#1


2  

I've modified your program a little bit. My approach was to accept a single line of input. If the input contains more than one token, ask the user to re-enter input. If there is only one input, check if the input is an integer, if not, as the user to again provide input.

我已经修改了你的程序了一点点。我的方法是接受一行输入。如果输入包含多个令牌,请要求用户重新输入输入。如果只有一个输入,检查输入是否为整数,如果不是,则作为再次提供输入的用户。

Seems to work for me:

似乎为我工作:

    Scanner scanner = new Scanner(System.in);

    String myString;
    int tokens;
    int number;

    do {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        tokens = new StringTokenizer(myString, " ").countTokens();
        try {
            number = Integer.parseInt(myString);
        } catch(NumberFormatException e) {
            tokens = 0;
            number = -1;
        }
    }while (tokens != 1);
    scanner.close();

    System.out.println(number);

Update: Alternate approach without using StringTokenizer

更新:不使用StringTokenizer的替代方法

    Scanner scanner = new Scanner(System.in);

    String myString;
    boolean validInput;
    int number;

    do {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        try {
            number = Integer.parseInt(myString);
            validInput = true;
        } catch(NumberFormatException e) {
            validInput = false;
            number = -1;
        }
    }while (validInput == false);
    scanner.close();

    System.out.println(number);

Update 2: Another approach using regular expressions to validate input before accepting it.

更新2:使用正则表达式在接受输入之前验证输入的另一种方法。

The Scanner allows us to use a regular expression to match the input. If the input matches the pattern, you can use it to accept the input. Otherwise, discard it and ask user to provide input again.

Scanner允许我们使用正则表达式来匹配输入。如果输入与模式匹配,则可以使用它来接受输入。否则,丢弃它并要求用户再次提供输入。

Here's the code:

这是代码:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a single integer");

    String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only

    while(scanner.hasNext(integerPattern) == false) {
        String x = scanner.nextLine();// capture and discard input.
        System.out.println("Enter a single integer. '" + x + "' is an invalid input.");
    }
    int number = scanner.nextInt(); // capture input only if it matches pattern.
    scanner.close();
    System.out.println("number: " + number);

Hope this helps!

希望这可以帮助!

#1


2  

I've modified your program a little bit. My approach was to accept a single line of input. If the input contains more than one token, ask the user to re-enter input. If there is only one input, check if the input is an integer, if not, as the user to again provide input.

我已经修改了你的程序了一点点。我的方法是接受一行输入。如果输入包含多个令牌,请要求用户重新输入输入。如果只有一个输入,检查输入是否为整数,如果不是,则作为再次提供输入的用户。

Seems to work for me:

似乎为我工作:

    Scanner scanner = new Scanner(System.in);

    String myString;
    int tokens;
    int number;

    do {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        tokens = new StringTokenizer(myString, " ").countTokens();
        try {
            number = Integer.parseInt(myString);
        } catch(NumberFormatException e) {
            tokens = 0;
            number = -1;
        }
    }while (tokens != 1);
    scanner.close();

    System.out.println(number);

Update: Alternate approach without using StringTokenizer

更新:不使用StringTokenizer的替代方法

    Scanner scanner = new Scanner(System.in);

    String myString;
    boolean validInput;
    int number;

    do {
        System.out.println("Enter a single integer");
        myString = scanner.nextLine();
        try {
            number = Integer.parseInt(myString);
            validInput = true;
        } catch(NumberFormatException e) {
            validInput = false;
            number = -1;
        }
    }while (validInput == false);
    scanner.close();

    System.out.println(number);

Update 2: Another approach using regular expressions to validate input before accepting it.

更新2:使用正则表达式在接受输入之前验证输入的另一种方法。

The Scanner allows us to use a regular expression to match the input. If the input matches the pattern, you can use it to accept the input. Otherwise, discard it and ask user to provide input again.

Scanner允许我们使用正则表达式来匹配输入。如果输入与模式匹配,则可以使用它来接受输入。否则,丢弃它并要求用户再次提供输入。

Here's the code:

这是代码:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a single integer");

    String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only

    while(scanner.hasNext(integerPattern) == false) {
        String x = scanner.nextLine();// capture and discard input.
        System.out.println("Enter a single integer. '" + x + "' is an invalid input.");
    }
    int number = scanner.nextInt(); // capture input only if it matches pattern.
    scanner.close();
    System.out.println("number: " + number);

Hope this helps!

希望这可以帮助!