在for循环中添加值

时间:2013-02-21 04:23:11

标签: java for-loop

我似乎无法弄清楚如何在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 个答案:

答案 0 :(得分:1)

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

 }        

答案 1 :(得分: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);
}

答案 2 :(得分: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;
}