java - 检查扫描仪输入是否只是一个整数

标签 java

我正在尝试创建一个简单的程序来验证用户的输入是否为正整数。但是,当我使用 Scanner.hasNextInt() 方法时遇到问题。如果输入包含一个整数,例如“5 6”,我的程序会将 6 作为整数读取。但是,我希望这样的语句无效并提示用户只需要输入一个整数值。因此程序会输出“请输入一个整数值:”。

这就是我的程序的样子:

import java.util.Scanner;

public class InputValidation {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        // INPUT VALIDATION FOR INTEGERS AND POSITIVE NUMBERS
        int input = 0;
        boolean validationSuccessful = false;

        System.out.print("Please enter the input: ");
        do {

            // validate that the input is an integer
            if (in.hasNextInt() == true) {
                input = in.nextInt();
            } else {
                System.out.print("Please enter an integer value: ");
                in.next();
                continue;
            }

            // validate that the input is positive
            if (input < 0) {
                System.out.print("Please print a POSITIVE integer: ");
                continue;
            } else {
                validationSuccessful = true;
            }
            System.out.println("The input is: " + input);
        } while (validationSuccessful == false);

    }
}

编辑: 我理解 next() 与 nextLine() 之间的区别。但是,我的问题是该行的验证方面实际上只是一个整数与包含整数的行。

最佳答案

要放弃一行,请使用

in.nextLine();

如果你使用

in.next();

它只读取一个单词/标记。 (“单词”是指空格之间的任何内容)

I only want to accept an integer value as the input, not just if the line contains an integer.

int value;
while(true) {
    // a number please.
    try {
         value = Integer.parseInt(in.nextLine());
         if (value > 0)
              break;
         // not positive. 
    } catch (NumberFormatException e) {
         // not an integer
    }
}

注意:0既不是正数也不是负数。

关于java - 检查扫描仪输入是否只是一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969612/

相关文章:

java - 为什么我的代码不能输出一组工作的所有子集?

java - Tomcat 5.5 中的 URL 路由和相对链接

java - 当按钮可见和不可见时,框布局组件会移动

java - java中执行cmd命令获取时间

java - 在两个数组中搜索值的算法

java - Java 中 HTTP/1.1 持久 ("Connection: Close") 连接的最佳库是什么?

java - 无法在Android上的外部存储上创建文件夹

java - 异常在线程 "main"java.lang.UnsatisfiedLinkError : RunnerClass. parsecmdline(ILjava/lang/String;)V

java - 如何获取发送数据包的主机名

java - 在 testng 的 @BeforeTest 中访问 spring 上下文