編寫使用while循環的程序。在循環的每次迭代中,提示用戶輸入一個數字 - 正數,負數或零。保持用戶輸入的總數,並保持用戶輸入的數量。只要用戶輸入「q」退出,程序應停止。用戶完成後,打印總計和用戶輸入的條目數量。用字符串終止循環。 (Java)
我可以讓這個程序工作,當我輸入一個數字如0,終止循環。但我不知道如何獲得它,以便一個字符串阻止它。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
你的意思是像試圖讀入一個字符串並檢查它是否等於'「q」'? (加上檢查用戶是否輸入了號碼等等) –