繁体   English   中英

如何在while循环中使用Java Scanner类使用OR条件?

[英]how to use OR condition in while-loop with java Scanner class?

我正在尝试使用Scanner对象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(); 

问题可能是您在条件中使用了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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM