首页 > 解决方案 > Sum of the first and last array elements in Java

问题描述

I'm using JB IntelliJ IDEA and trying to create a program which finds the sum of the first and last elements of a randomly generated array using the sum() method. My problem is that an error occures, please help me.

Here is my code:

package com.company;
import java.util.Random;
public class Main {
    public static int sum(int[] array) {
        int x = array[0];
        int y = array[9];
        int z = x + y;
        return z;
    }
    public static void main(String[] args) {
        int[] array = new int[10];
        Random rand = new Random();
        for (int i = 0; i < array.length; i++) {
            int j = rand.nextInt(50);
            System.out.println(sum());
        }
    }
}

and error:

Error:(15, 32) java: method sum in class com.company.Main cannot be applied to given types;
required: int[]
found: no arguments
reason: actual and formal argument lists differ in length

标签: java

解决方案


** Error:(15, 32) java: method sum in class com.company.Main cannot be applied to given types;

required: int[]

found: no arguments

reason: actual and formal argument lists differ in length

Going through the Error itself says everything about the issue:

required: int[]

found: no arguments

It is saying that it required an array of data type int which is missing(no arguments) and that is why actual and formal argument lists differ in length

Hence, Sum function requires an array to be passed as a parameter.

Also, you are getting random integer value in a integer variable j = rand.nextInt(50); but not assigning it to the array which is just wasting the loop to run unnecessarily 10 times.

Instead of assigning it to j we can directly assign it to the array and fill array with the random integers before passing it to the method sum(array):

Try this updated code with the changes needed:

package com.company;
import java.util.Random;
public class Main {
    public static int sum(int[] array) {
        int x = array[0];
        int y = array[9];
        int z = x + y;
        return z;
    }
    public static void main(String[] args) {
        int[] array = new int[10];
        Random rand = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = rand.nextInt(50);
        }
        System.out.println(sum(array));
    }
}

推荐阅读