9

sumAll()任意の数の整数を取り、それらの合計を返すJava メソッドを作成する必要があります。

sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20

これを行う方法がわかりません。

4

7 に答える 7

9
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 
于 2013-06-16T05:43:39.937 に答える
1
import java.util.Scanner;

public class SumAll {
    public static void sumAll(int arr[]) {//initialize method return sum
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.println("Sum is : " + sum);
    }

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);//create scanner object 
        System.out.print("How many # you want to add : ");
        num = input.nextInt();//return num from keyboard
        int[] arr2 = new int[num];
        for (int i = 0; i < arr2.length; i++) {
            System.out.print("Enter Num" + (i + 1) + ": ");
            arr2[i] = input.nextInt();
        }
        sumAll(arr2);
    }

}
于 2014-08-30T11:52:25.220 に答える