Michael Miller
Michael Miller

Reputation: 71

Accessing an array in another method

I am trying to access an array in a separate method that it is initialized in.

public void initializeArray()
{                
    String sentences[] = new String[5];

    for(int i=0; i<5; i++)
    { 
        sentences[i] = i+1;
    }
}

public void printArray()
{
    for(int i=0; i<5; i++)
    {
        System.out.println(sentences[i]);
    }
}

I know that I could do this in one for loop, but can someone explain how I could print the array this way? I need to access the sentences array in a separate method that it is initialized in. I tried to make an instance of the array at the top of the program but it gives me an error saying "Local variable hides a field".

Upvotes: 1

Views: 40860

Answers (9)

shoban Raj 149
shoban Raj 149

Reputation: 1

public class Main {

    static void add(int[] array1) {
        int sum = 0;
        for (int i = 0; i < array1.length; i++) {
            sum += array1[i];
        }
        System.out.println(sum);
    }
         static void sub(int[] array2){
            int sum=0;
            for(int j=0;j< array2.length;j++) {
                sum-=array2[j];
            }
            System.out.println(sum);
        }



        public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
            System.out.print("Enter the number of int that u r gonna enter = ");
        int num= input.nextInt();
        int Mainarray[]= new int[num];
            System.out.println("Enter the elements = ");
        for(int i=0;i<num;i++){
            Mainarray[i]= input.nextInt();
        }
        System.out.println("ENTER 1 TO ADD"+"\n"+"ENTER 2 TO SUBTRACT");
        int num2= input.nextInt();
        if(num2==1) {
            add(Mainarray);
        }else if(num2==2){
            sub(Mainarray);
    }
    }
}

Upvotes: 0

Local Maximum
Local Maximum

Reputation: 21

You are declaring the variable sentences[] inside the method initializeArray(). Because of this, it doesn't exist outside of this method. As soon as the method finishes, it disapears. Other methods can't use the variable.

You should declare the variable outside the method, like this:

public class Example {

    static String sentences[] = new String[5];;

    public static void main(String[] args) {
        initializeArray();
        printArray();
    }

    public static void initializeArray() {
        for (int i = 0; i < 5; i++) {
            sentences[i] = "" + (i + 1);
        }
    }

    public static void printArray() {
        for (int i = 0; i < 5; i++) {
            System.out.println(sentences[i]);
        }
    }
}

That way, you can use it anywhere in this class. If you want to use it somewhere else, too, add the keyword public before it.

Upvotes: 2

user2575725
user2575725

Reputation:

I tried to make an instance of the array at the top of the program but it gives me an error saying "Local variable hides a field".

You already have a instance variable, so remove the local variable within method:

public void initializeArray()
{                
    //String Sentences[] = new String[5];
    ...
}

Also don't use magic numbers like you did in for-loop:

for(int i=0; i<5; i++)//use `sentences.length` instead of `5`

Upvotes: 2

gran_profaci
gran_profaci

Reputation: 8463

The printArray method knows nothing of sentences right?

Java is pass by value and requires you to literally give the value of a piece of data to a method in order for the method to crunch on it. Global values are basically values that are known to every object.

Thus, you need something that will tell both initializeArray and printArray that there is this piece of data sentences that should be worked on.

// A Calling Function
public void initializeAndPrintStringArray
{
    // Get the initialized Sentences Array
    String[] sentences = initializeArray();

    // Print this Initialized Array
    printArray(sentences)
}

// For doing this, you need to change the definitions of your methods

public String[] initializeArray()
{                
    String[] sentences = new String[5]; // You have a spelling mistake here

    for(int i=0; i<5; i++)
    { 
        sentences[i] = i+1;
    }
    return sentences
}

public void printArray(String[] sentences)
{
    // Don't assume the length will always be 5 or something you know beforehand.
    for(int i=0; i<sentences.length; i++) 
    {
        System.out.println(sentences[i]);
    }
}

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44813

Have your initializeArray return an Array as in

public String[] initializeArray () {

   ...
   return sentences;
}

Change yourprintArray to

public void printArray (String [] arr) {
   ...
   System.out.println(arr[i]);
}

Imagine a main method like

String myArr [] = initializeArray  ();
printArray (myArr);

Upvotes: 0

DWright
DWright

Reputation: 9500

The following should work:

class MyClass
{

    private String sentences[] = new String[5];

    public void initializeArray()
    {                
        for(int i=0; i<5; i++)
        { 
            sentences[i] = i+1;
        }
    }

    public void printArray()
    {
        for(int i=0; i<5; i++)
        {
            System.out.println(sentences[i]);
        }
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

There are two ways to access the same array from two methods:

  • Access the array through an instance variable of array type, or
  • Pass the array to methods as a parameter.

The first approach looks like this:

class TestInstanceVar {
    private String[] sentences = new String[5];
    public static void main(String[] args) {
        TestInstanceVar obj = new TestInstanceVar();
        obj.initializeArray();
        obj.printArray();
    }
    public void initializeArray() {
        ...
    }
    public void printArray() {
        ...
    }
}

Here, the methods access sentences as an instance variable, which is shared across all methods running on the same instance.

The second approach looks like this:

class TestPassArray {
    public static void main(String[] args) {
        private String[] sentences = new String[5];
        initializeArray(sentences);
        printArray(sentences);
    }
    public static void initializeArray(String[] sentences) {
        ...
    }
    public static void printArray(String[] sentences) {
        ...
    }
}

Here the array is created in the main method, and is passed explicitly as a parameter to the initialization and printing methods. Note that the methods are marked static, and accessed without creating an object.

Upvotes: 0

Gentatsu
Gentatsu

Reputation: 717

Make sentences a global variable or parameters to both functions.

Upvotes: 0

MadConan
MadConan

Reputation: 3767

Change the signature of your printArray method to be

public void printArray(String[] sentences){...}

So you have

public void initializeArray(){
   int arraySize = 5;
   String[] sentences = new String[arraySize];
   for(int i=0; i<arraySize; i++){
        sentences[i] = new String(i+1);
   }
   printArray(sentences);
}

Upvotes: 0

Related Questions