Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

Not able to give inputs to a function java.

In this example, i want to add the contents of the two arrays, but I am not able to get how should the input be given. For example, in this case, "invalid assignment operator" error is showing up, for the line int[] a = new int[1,2]. I want to know how to call the function addarr, using the arrays a and b.

public class arradd {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] a = new int[1,2];
    int[] b = new int[3,4];
    new arradd.addarr(a,b);
}

public void addarr(int[] arr1, int[] arr2){
    int total = 0;
    for(int i = 0; i < arr1.length; i++){
        total += arr1[i];
    }
    for(int i = 0; i < arr2.length; i++){
        total += arr2[i];
    }
    System.out.println(total);
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of your problems why the "invalid assignment operator" error is showing up is because you can't do this in java

int[] a =new int[1,2];    // will give you a compiler error.

the parameter inside the square bracket actually means the size of the array.

int[] a=new int[2];

here 2 means the size of the array 'a'.

if you want to declare the contents for the array, do this

 int[] a=new int[2]{1,2};

this is exactly what you need ...where the value inside the square bracket tells the compiler the size of the array 'a' and the values inside the curly braces tells the contents what those are the two contents of the given array 'a'.

And you dont need new operator to or the class name itself to call a method within the class. Just do a

addarr(a,b);

to call the function and your function would be invoked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...