Accessing and filling array(s) by its name in the main method of a java class (created via member function )

user10602498 :

I have a program in which I should create a class that has a member function which creates arrays of different simple data types. I instantiate a class in the main method, i.e I make a object of this class, and invoke the createArray method. When I try to fill - in the array with the same type of data using Arrays.fill(name,startIndex, endIndex, value) it could not find an array which such name. I would like to ask you why is that?

import java.lang.reflect.Array;
import java.util.Arrays;

    public class MainClass {
      public void createArray(){
      int [] ints = new int[10];
      }
    }
    class Test{
        public static void main(String[] args) {
            MainClass mcl = new MainClass();
            mcl.createArray();
            for (int i = 0;i<10;i++){
                //cannot resolve symbol ints - why?
                Arrays.fill(ints,0,9,8);
            }
        }
    } 
dzenang :

If you don't want to change createArray method signature, you can store your array in a class attribute and create getter method for it. Here is some code:

import java.util.Arrays;

class MainClass {

    private int[] ints;

    public void createArray(){
        this.ints = new int[10];
    }

    public int[] getInts() {
        return ints;
    }
}
class Test{
    public static void main(String[] args) {
        MainClass mcl = new MainClass();
        mcl.createArray();
        for (int i = 0;i<10;i++){
            //cannot resolve symbol ints - why?
            Arrays.fill(mcl.getInts(),0,9,8);
        }
    }
}

But since createArray is already public, better approach is probably to change it's signature to return int[], example code for that case:

import java.util.Arrays;

class MainClass {

    private int[] ints;

    public int[] createArray(){
        this.ints = new int[10];
        return ints;
    }

}
class Test{
    public static void main(String[] args) {
        MainClass mcl = new MainClass();
        mcl.createArray();
        for (int i = 0;i<10;i++){
            //cannot resolve symbol ints - why?
            Arrays.fill(mcl.createArray(),0,9,8);
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141834&siteId=1