下面的 while 回圈運行了額外的時間。我正在嘗試執行一個用戶輸入,該輸入接受來自用戶的 10 個有效數字并列印它們的總和。但是,while 回圈執行了額外的時間并要求輸入第 11 個輸入。
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i ;
System.out.println("Enter number " "#" i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum = userChoiceNumber;
}else{
System.out.println("Invalid Input");
}
}
}
System.out.println("The sum of your entered numbers are = " sum);
}
uj5u.com熱心網友回復:
除了那些很棒的評論,如果你得到一個 VALID 輸入,你應該只增加“i”:
while(i <= 10) {
System.out.print("Enter number " "#" i ": ");
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum = userChoiceNumber;
i ;
}else{
System.out.println("Invalid Input");
sc.next();
}
}
請注意,當您輸入錯誤時,您需要使用“sc.next()”將其洗掉。
uj5u.com熱心網友回復:
首先 - 確保您的格式正確。(我已經縮進了你的回圈,將你的輸出移動到主類中,修復了一些大括號/回圈結尾)。
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i ;
System.out.println("Enter number " "#" i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum = userChoiceNumber;
}
else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " sum);
}
好的 - 所以運行代碼,我發現詢問的次數是正確的,但是輸入屬性顯示錯誤的數字,第一個輸入提示從 2 開始,最后一個輸入提示從 11 開始。
原因是i 在請求輸入之前運行,因此它在輸出之前計數。
這可以通過將 saidi 移到 else 子句下方來輕松解決 - 如下所示:
else{
System.out.println("Invalid Input");
}
i
}
uj5u.com熱心網友回復:
這里的主要問題是您在 while 回圈開始時增加了變數。如果這就是你要找的,那很好,但是如果你想在回圈達到 10 時停止回圈,你需要讓它像while(i < 10)在i 回圈結束時一樣,那么你可以做while(i <= 10)
Ex:
i = 0;
while(i < 10){
i ;
//code here
}
這將使使用 i 的代碼使用 1 到 10 之間的值。使用 <= 將使用 1 到 11 之間的值。
另一個例子:
i = 0;
while(i < 10){
//code here
i ;
}
這將使使用 i 的代碼使用 0 到 9 之間的值。使用 <= 將使用 0 到 10 之間的值。
人們做增量回圈的另一種方法是做一個for回圈而不是一個while回圈,這看起來像:
for(int i = 0; i < 10; i ){
//code here
}
這也允許您創建一個僅在回圈內的變數,因此您可以在 for 回圈內創建它,而不是在方法的開頭或回圈之前創建它。但是,如果該變數在其他地方使用,這并不好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/445246.html
