[英]Using an if statement with a while loop?
我正在嘗試做這個問題:
設計一個程序,該程序讀取以-9999結尾的數字列表,並打印出輸入的總和。
我正在修改程序,以便只對1
到100
之間的值求和,並且如您所見,我已經嘗試實現if
語句。 但是,什么都沒有改變,這部分使我難過。 我已經堅持了很長時間,代碼如下:
import java.util.Scanner;
public class Summing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Number, Sum = 0;
System.out.println("Enter a list of whole numbers, finished by -9999");
Number = sc.nextInt();
if (Number > 0 || Number < 100);
while (Number != -9999) {
Sum = Sum + Number;
Number = sc.nextInt();
}
System.out.println("Sum is " + Sum);
}
}
將if
語句移入循環。 現在, if
語句在進入循環之前僅執行一次 (由於緊隨該條件之后的;
,它什么也不做)。 您希望將其用於每個值。
另請注意,我更改了||
到&&
。 否則,例如101將會匹配,不在0到100之間。最后, a = a + b
總是可以更簡潔地寫為a += b
。
while (Number != -9999) {
if (Number > 0 && Number < 100) {
Sum += Number;
}
Number = sc.nextInt();
}
作為另一種樣式上的更改(這幾乎是通用的慣例),您應該考慮將變量更改為小寫名稱。
您將if
放在了while
循環之前,並且它有一個空(=完全不執行任何操作)。 無論如何,條件也是錯誤的,因為Number > 0 || Number < 100
Number > 0 || Number < 100
將匹配所有數字。 您要更改||
到&&
。
這應該工作:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Number, Sum = 0;
System.out.println("Enter a list of whole numbers, finished by -9999");
Number = sc.nextInt();
while (Number != -9999) {
if (1 < Number && Number < 100) {
Sum += Number;
}
Number = sc.nextInt();
}
System.out.println("Sum is " + Sum);
}
您相當接近,但是if測試應該在循環中(並且您可能應該使用{
和}
大括號)。 按照慣例,Java變量名稱以小寫字母開頭,我更喜歡使用+=
運算符添加到sum
。 另外,要檢查您的范圍,您在邏輯上需要使用and(而不是or)。 就像是,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a list of whole numbers, finished by -9999");
int number = sc.nextInt();
int sum = 0;
while (number != -9999) {
if (number > 0 && number < 100) {
sum += number;
}
number = sc.nextInt();
}
System.out.println("Sum is " + sum);
}
您的if在while循環之前。 將其放入循環中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.