2017-08-09 209 views
-2

我正在編寫一個程序,要求用戶輸入正整數並計算從1到該數字的總和。需要一些提示我做錯了什麼。用於循環以獲取數字總和的Java

下面是代碼:

public static void main(String[] args){ 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Enter a positive integer"); 
    int getNumber=keyboard.nextInt(); 
    int x; 
    int total = 0; 
    for (x=1;x<=getNumber;x++) { 
     total=x+1; 
    } 
    System.out.println(total); 
} 
+3

做'總=總+ x'代替'總= X + 1',會做。 – GadaaDhaariGeek

+0

您可以調試並找出問題。 – Nipun

+0

什麼是調試方法? – Mariusz

回答

0

邏輯應從

total=x+1; // you evaluate total each iteration to initialize it with x+1 

改爲

total=total+x; // you keep adding to the existing value of total in each iteration 
0

得到的總和從1到要輸入數字每次用新號碼x增加total

so。

也有提示:

你想用你的循環申報int x。刪除int x並執行以下操作:

for (int x=1; x<=getNumber; x++) { 
    total = total + x; 
} 
0

您的問題是:

後的總價值是錯誤的,因爲這行:

total=x+1; 

它應該是:

total = total + x; 
0

更改爲:

total=x+1; 

這樣:

total=total+x; 
0

嘗試以下代碼:

public static void main(String[] args){ 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter a positive integer"); 
     int getNumber = keyboard.nextInt(); 
     int x; 
     int total = 0; 
     for (x=1;x <= getNumber;x++) { 
      total += x; 
     } 
     System.out.println(total); 
    }