[英]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.