我正在尝试使用扫描程序对象sc 来读取用户输入的整数,并且需要评估它是否大于0.所以我在while()中设置以下OR条件来检查是否为空行或输入数小于0.但程序在遇到无效输入后不接受输入。任何帮助表示赞赏。
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt() || sc.nextInt() <= 0)
{
System.out.println("Invalid input\n the number needs to be greater than 0");
sc.next();
}
int number = sc.nextInt();
答案 0 :(得分:1)
问题可能是你在条件下消耗了nextInt。你应该把它读成一个变量:
包裹测试;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
int input=-1;
while(input<0){
while (!sc.hasNextInt()) {
if(sc.hasNext()){
String s = sc.next(); /* read things that are not Integers */
System.out.println("Invalid input:" + s);
}
}
input = sc.nextInt();
if(input<0){
System.out.println("Please input a positive integer.");
}
}
System.out.println("Valid input was "+input);
}
}