如何在 java Scanner 类的 while-loop 中使用 OR 条件



我正在尝试使用扫描仪对象sc从用户的输入中读取整数,并需要评估它是否大于0。所以我在 while() 中设置了以下 OR 条件来检查它是空行还是输入数字小于 0。但程序在遇到无效输入后不会接受输入。任何帮助,不胜感激。

 Scanner sc = new Scanner(System.in);
 while (!sc.hasNextInt() || sc.nextInt() <= 0)
        {
            System.out.println("Invalid inputn the number needs to be greater than 0");
            sc.next();
        }
        int number = sc.nextInt(); 

问题可能是您在该条件下消耗了 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);
    }
}

最新更新