如何返回数组来计算总数并找到最大值?

时间:2016-11-30 00:54:38

标签: java arrays return

我试图返回数组中所有值的总和,同时还尝试将最大值返回到main方法,但是,程序声明我在返回总数和返回数字时有错误。错误状态为“类型不匹配:无法从int转换为int []。”

public static void main(String[] args) {
    Scanner number = new Scanner(System.in);
    int myArray[] = new int[10];
    for(int i = 0; i <= myArray.length-1; i++ ) {
        System.out.println("Enter Number: ");
        int nums = number.nextInt();
        myArray[i] = nums;
   }
   int [] sum = computeTotal(myArray);
   System.out.println("The numbers total up to: "+sum);
   int [] largest = getLargest(myArray);
   System.out.println("The largest number is: "+largest);
}

public static int[] computeTotal(int myArray[]) {
    int total = 0;
    for (int z : myArray){
        total += z;
    }
    return total;
}
public static int[] getLargest(int myArray[]) {
    int number = myArray[0];
    for(int i = 0; i < myArray.length; i++) {
        if(myArray[i] > number) {
            number = myArray[i]; 
        }
    }
    return number;
}

2 个答案:

答案 0 :(得分:0)

可能在java8中有更简单的方法来获得最大值和总和。

int sum = Arrays.stream(new int[] {1,2, 3}).sum();            //6 
int max = Arrays.stream(new int[] {1,3, 2}).max().getAsInt(); //3

答案 1 :(得分:0)

方法computeTotalgetLargest应该将返回类型更改为int。请参考:

public static void main(String[] args) {
        Scanner number = new Scanner(System.in);
        int myArray[] = new int[10];
        for(int i = 0; i <= myArray.length-1; i++ ) {
            System.out.println("Enter Number: ");
            int nums = number.nextInt();
            myArray[i] = nums;
       }
       int sum = computeTotal(myArray);
       System.out.println("The numbers total up to: "+sum);
       int largest = getLargest(myArray);
       System.out.println("The largest number is: "+largest);
    }

    public static int computeTotal(int myArray[]) {
        int total = 0;
        for (int z : myArray){
            total += z;
        }
        return total;
    }
    public static int getLargest(int myArray[]) {
        int number = myArray[0];
        for(int i = 0; i < myArray.length; i++) {
            if(myArray[i] > number) {
                number = myArray[i]; 
            }
        }
        return number;
    }

希望这有帮助。