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

家住魔仙堡 提交于 2019-12-25 07:29:33

问题


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?


回答1:


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:

  • The Java Tutorial. Operators
  • The Java Tutorial. Primitive Data Types
  • The Java Tutorial. Arrays



回答2:


double[] results = sum(new double[] {0,1,2}, new double[] {2,2,3});


来源:https://stackoverflow.com/questions/23397622/bluej-java-program-returning-a-new-array-containing-the-componentwise-sum-of-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!