BlueJ / Java program returning a new array containing the componentwise sum of its arguments

StackOverflow https://stackoverflow.com/questions/23397622

  •  13-07-2023
  •  | 
  •  

문제

The following code returns a new array containing the componentwise sum of its arguments (assuming their length is the same), for example if the input arrays are {0,1,2} and {2,2,3} then the out out will be {2,3,5} and if the input arrays have different numbers of elements, the method should return null.

public class Sum
{
    public static double[] sum(double a[], double b[]){

    if (a.length != b.length)
    return null;
    int[] s = new double[a.length];
    for(int i=0; i<a.length; i++)
    s[i] = a[i] + b[i];
    return s;
    }
 public static void main(String[] args) {
        //calling the method to seek if compiles
        double[] results = Sum.sum(new double[] {0,1,2} + {2,2,3});
        //printing the results
        System.out.println(java.util.Arrays.toString(results));
    }
}

As I have mentioned before normally when I run this program code above I supposed to have {2,3,5} as result, but I am getting nothing. In fact I cannot able to compile it in BlueJ, I am keep getting the error message saying: illegal start of expression for this line: double[] results = Sum.sum(new double[] {0,1,2} + {2,2,3});

So I assume I did syntax error, but I am not too sure, how can I get rid of it, any suggestions?

도움이 되었습니까?

해결책

There are two problems in your code:

  • The + operator is allowed for primitive numeric types only. In this line of code:

    Sum.sum(new double[] {0,1,2} + {2,2,3});
    

    You're trying to apply + operator for double[] variables, which is not allowed, thus getting the exception. Since the method already accepts 2 arguments double[], then send both double[]s by separating them using comma ,.:

    Sum.sum(new double[] {0,1,2}, new double[] {2,2,3});
    
  • This line of code:

    int[] s = new double[a.length];
    

    You cannot initialize an array of primitive type with an array of another primitive type. int[] and double[] are complete different classes. So, instead change the type declaration for your variable:

    double[] s = new double[a.length];
    

More info:

다른 팁

double[] results = sum(new double[] {0,1,2}, new double[] {2,2,3});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top