[英]Exiting a while loop on java
我正在嘗試創建一個使用getInt方法的程序,以確保用戶輸入一個正數。 我到目前為止
public class Binary {
public static void main(String [ ] args) {
Scanner CONSOLE = new Scanner(System.in);
int decimal=getInt(CONSOLE, "Enter a positive integer: ");
}
public static int getInt(Scanner CONSOLE, String prompt) {
System.out.print(prompt);
while (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
System.out.println(prompt);
}
int posInt=CONSOLE.nextInt();
while (posInt <= 0) {
System.out.println("Not a positive integer; try again.");
CONSOLE.next();
System.out.println(prompt);
}
return CONSOLE.nextInt();
}
}
出現問題是,當用戶確實輸入正數時,它仍然無視輸入並要求用戶再次輸入正整數。 我想我只是沒有正確退出循環,但不確定如何。
您的問題是return CONSOLE.nextInt();
在方法的最后,您正在調用CONSOLE.nextInt()
,它再次要求輸入。
返回posInt
,就可以了。
祝您好運,HTH
就像其他人所說的,您可以返回posInt
,您應該會很好。
但是我對您的getInt
方法有一些建議:
public static int getInt(Scanner CONSOLE, String prompt) {
//initialize vars
boolean valid = false;
int posInt = 0;
//while the input is not valid, loop over the evaluation
while(!valid){
System.out.print(prompt);
if (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
//"continue" stops the loop here and starts it from the beginning
continue;
}
posInt=CONSOLE.nextInt();
if (posInt > 0) {
//valid = true will get us out of the loop
valid = true;
}else {
System.out.println("Not a positive integer; try again.");
}
}
return posInt;
}
如果之前的輸入無效,則此代碼將從頭開始重新評估輸入。
在代碼中,如果輸入負整數,則系統將提示您重新輸入一個數字。
但是由於您已經在while (posInt <= 0)
循環中,所以它不會重新檢查您是否實際輸入了有效的輸入。
我提供的代碼從頭開始重新評估下一個輸入,直到發現有效為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.