Question

I am having an issue returning a new array from one method to my main method. I have been doing some research and unfortunately I can't seem to find an answer? The answers that I have found seem quite detailed and they are not actually what I am looking for.

Here is my code:

import java.util.*;

public class SquareArray
{


public static void main (String[] args){

    double a[] = new double[5];

    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    a[3] = 3;

    square(b);
}

public static double[] square(double[] a){

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

    for(int i = 0; i < a.length-1; i++){
        b[i] = a[i] * a[i];
        System.out.println(b[i]);
    }

    return (b); 
    }
}

All the method is required to do is to square the numbers in the original array, store in a new array and return to the main method.

Please forgive any errors in my code as I am still learning Java.

Many thanks.

Was it helpful?

Solution

Your error is because you are passing a variable that isn't defined either in the Main method or globally. You should change the line to square(a) to pass in the array you defined just before it.

Secondly, your square method has a return type of double[], but you aren't assigning it to anything. If all you want to do is show the squared values, you could simply make it a method of return type void. On the other hand, if you do want to actually use the array returned by this method, then you will need to declare another variable and assign to it like so:

double[] b = square(a);

The main advantage is that, if you need to use the array returned by this method, say, 10 times later in your code, you can just use the variable instead of calling the method 10 times.

OTHER TIPS

If you want to get the returning value from your method then pass the current array and pass the method to your current array;

 a = square(a);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top