简体   繁体   English

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

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

I am trying to use Scanner object sc to read in an integer from user's input and need to assess whether it's greater than 0. So I set the following OR conditions in the while() to check whether it's an empty line or the input number is less than 0. But the program does not take inputs after it encountered an invalid input. 我正在尝试使用Scanner对象sc从用户输入中读取一个整数,并且需要评估它是否大于0。因此,我在while()中设置了以下OR条件,以检查它是否为空行或输入数字是否为小于0。但是程序在遇到无效输入后不接受输入。 Any help is appreciated. 任何帮助表示赞赏。

 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(); 

The problem is probably that you're consuming the nextInt in the condition. 问题可能是您在条件中使用了nextInt。 You should read it into a variable: 您应该将其读入变量:

package test; 包装测试;

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