2013-02-21 170 views
-1

我似乎無法弄清楚如何在for循環中添加值。我應該得到的輸出是這樣的:在循環中添加值

How many numbers? 
3  //user inputs numbers desired. 
number please 
1 
2 
3 
Total is 6 

任何幫助將不勝感激!

import java.util.Scanner ; 
public class AddNumbers { 

public static void main(String[] args) { 
    int sum = 0; 
    int count = 1; 
    Scanner scan = new Scanner(System.in); 
     System.out.println("How many numbers?"); 
     int n = scan.nextInt(); 

     for(int i=0; i <= n; i++){ 
      System.out.println ("number please"); 
      int c = scan.nextInt(); 

      //stuck 

     }   
     System.out.println("Total is " + sum); 
} 
} 
+3

只需添加'總和+ = C;'在循環 你的循環也應該是'for(int i = 0; i iTech 2013-02-21 04:24:56

+0

非常感謝!我對Java編碼非常缺乏經驗。 – 2013-02-21 04:33:26

回答

1
for(int i=0; i < n; i++){ 
    System.out.println ("number please"); 
    int c = scan.nextInt(); 
    sum =sum+c; // add this 

}   
+0

無效答案!你已經重複了_OP_所犯的錯誤。 '<='不對,應該只是'<' – SudoRahul 2013-02-21 04:50:50

+0

@ R.J謝謝。現在更正。 – 2013-02-21 04:58:28

0

只需添加一個可變的for循環外並添加值以該變量計算總:

int n = scan.nextInt(); 
int total = 0; 
for(int i=0; i <= n; i++){ 
    System.out.println ("number please"); 
    int c = scan.nextInt(); 
    //stuck 
    total += c; 
} 
+0

無效的答案!你已經重複了_OP_所犯的錯誤。 '<='是錯誤的,它應該只是''' – SudoRahul 2013-02-21 04:50:03

+0

@ R.J但他沒有卡在那裏,雖然你是對的,這是OP的邏輯錯誤。 – Abubakkar 2013-02-21 05:32:56

1
public static void main(String[] args) 
{ 
    Scanner scan = new Scanner(System.in); 
    int sum=0; 
    System.out.println("How many numbers?"); 
    int count = scan.nextInt(); 
    System.out.println("number please"); 

    // This is what you need to change 
    for(int i=0; i<count; i++) 
    { 
     sum += scan.nextInt(); 
    } 

    System.out.println("Total is " + sum); 
}