Saurus
Saurus

Reputation: 79

Values of an array, in a method, cannot be returned to main (java)

I am new to Java and I am trying too figure out how the return statement works with arrays. In the program I am trying to return the array beeing populated in the 'squares' method to main. My intentions are to write a method int[] squares(int n) that returns an array with the squares of all natural number from 1 to n. Currently I am just testing and trying to figure out how to pass myArray. The error I get is

Array8.java:7: error: cannot find symbol int[] mainArray = myArray;"

public class Array8{

  public static void main(String[] args)
  {
    squares(3);
    int[] mainArray = myArray; //cannot find symbol

    for(int i = 0; i < mainArray.length; i++){
      System.out.println(mainArray[i]);
    }
  }

  public static int[] squares(int n){

    int[] myArray = new int[n];
    for(int i = 0; i < myArray.length; i++){
      myArray[i] = 1 + i;
    }
    return myArray;
  }

}

Upvotes: 0

Views: 1116

Answers (4)

Nate
Nate

Reputation: 65

you haven't initialized your myArray in the main method, the myArray form your squares() method is out of the scope of your main method.

public static void main(String[] args)
{
    int[] myArray = squares(3);
    int[] mainArray = myArray; 

    for(int i = 0; i < mainArray.length; i++){
      System.out.println(mainArray[i]);
    }
}

Will fix your issue but a cleaner look would be.

{
int[] mainArray = squares(3); 

for(int i = 0; i < mainArray.length; i++){
  System.out.println(mainArray[i]);
    }
}

Upvotes: 0

Sekhar
Sekhar

Reputation: 61

you created int[] myArray as part of squares() method which is local variable. If you want to use that you can create it as global variable and then you can assign.

If you want to test how the int[] return type works you can change your code int[] mainArray = myArray; to int[] mainArray = squares(3); - in this line the retun int[] will be assign to mainArray.

Upvotes: 0

Shubham Saraswat
Shubham Saraswat

Reputation: 559

You need to collect the output that you are returning from the squares method to your variable mainArray like below. The variable myArray is a local variable of the method square and hence wont be available inside your main method.

int[] mainArray = squares(3);

Upvotes: 2

Jacob Kaddoura
Jacob Kaddoura

Reputation: 175

myArray is local to the squares() method. You can only access it from that method.

What you want is:

mainArray = squares(3);

Upvotes: 0

Related Questions