-4

我是Java新手,我现在正在学习。我想创建一个小程序,可以总结我在程序中显示的所有数字。我的程序的主要思想要求我提供许多数字。这是循环:

for (int k = 1; k <= 6 ; k++){
    System.out.println("Type " + k +". number");
    f = userInput.nextInt();
}

我想知道我的程序如何总结我所有的数字?

4

5 回答 5

1

您需要声明一个变量来保存总和:

int f, sum = 0;
for (int k = 1; k <= 6 ; k++){

    System.out.println("Type " + k +". number");
    f = userInput.nextInt();
    sum += f;
}
于 2013-10-27T18:14:29.100 回答
0

Try this

    int answer = 0;
    for (int k = 1; k <= 6 ; k++){

        System.out.println("Type " + k +". number");
        f = userInput.nextInt();
        answer += f; 

    }
    System.out.println(answer);
于 2013-10-27T18:14:35.743 回答
0
// assuming userInput is a Scanner

int sum = 0;

int f;

for (int k = 1; k <= 6 ; k++){

    System.out.println("Type " + k +". number");
    f = userInput.nextInt();

    sum += f;

}

// sum now holds the sum of all numbers
于 2013-10-27T18:15:15.630 回答
0

Assuming you did create a scanner object before this segment of code you can simply have a sum variable that hold the sum of your inputs.

       int sum =0;
       for (int k = 1; k <= 6 ; k++){

            System.out.println("Type " + k +". number");
            f = userInput.nextInt();
            sum += f;    
        }
于 2013-10-27T18:17:00.233 回答
0

您需要使用另一个变量来存储总和。

int sum = 0;

for (int k = 1; k <= 6; k++) {

    System.out.println("Type " + k +". number");

    f = userInput.nextInt();

    sum = sum + f;
}
于 2013-10-27T18:14:19.213 回答