-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);
}
}
4

3 回答 3

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);
}
于 2013-02-21T04:44:20.090 回答
1
for(int i=0; i < n; i++){
    System.out.println ("number please");
    int c = scan.nextInt();
    sum =sum+c; // add this

 }        
于 2013-02-21T04:24:23.023 回答
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;
}  
于 2013-02-21T04:25:25.017 回答