[英]While Loops in Java Problems
現在我們正在學習 while 循環 - 這就是挑戰。 “程序應該反復提示用戶輸入一個數字。保持用戶輸入數字的運行總數,並記錄用戶輸入的數量。只要用戶輸入的東西不是數字,程序就應該停止整數。當用戶完成后,打印用戶輸入的條目數及其總和。”
“與此程序的示例交互可能如下所示:程序:輸入一個整數以繼續或輸入一個非整數值以完成。然后按回車。
用戶:2
程序:輸入一個整數以繼續或輸入一個非整數值以完成。 然后按回車。
用戶:6
程序:輸入一個整數以繼續或輸入一個非整數值以完成。 然后按回車。
用戶:89
程序:輸入一個整數以繼續或輸入一個非整數值以完成。 然后按回車。
用戶:q
程序:您輸入了 3 個整數。 您輸入的總和是 97。”
這是我到目前為止所擁有的。
import java.util.Scanner;
public class InputSequence
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int sum = 0;
int total = 0;
while (scan.hasNextInt())
{
scan.next();
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int input = scan.nextInt();
sum = input + input;
total = total + 1;
}
System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
}
}
我只是有點困惑,因為我的交互似乎在 while 循環中每 2 次跳過 system.out.println ,然后不將第一個輸入計入總數。 我相信總和也不總是正確計算。 另外,如果我輸入了很多整數,然后輸入一個非整數來結束程序,我將收到一個錯誤而不是結束消息。 但是,假設我先輸入兩個整數,然后輸入一個字符串,我會得到結束消息。
您的問題在於可以刪除的scan.next()
中的用法,並且應該正確顯示System.out.println
。
.next()
方法是nextInt()
的通用方法,它返回一個String
。
您可以做的另一件事是從while
循環切換到do while
以防止您重復此行兩次:
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
一個例子是:
Scanner scan = new Scanner(System.in);
int sum = 0;
int total = 0;
do {
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int input = scan.nextInt();
sum = input + input;
total = total + 1;
} while (scan.hasNextInt());
System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.