我正在尝试创建一个简单的程序来验证用户的输入是否为正整数。但是,当我使用 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/