Accessing arrays with methods

后端 未结 4 1984
旧时难觅i
旧时难觅i 2021-01-24 02:23

Hi guys i\'m just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method? The design look like this:



        
4条回答
  •  情话喂你
    2021-01-24 02:58

    There a two options:

    • You declare that array as instance variable
    public class Arrays {
    
        private int arraySize = 2;
        private float array[];// Declare array
    
        public void initializeArray() {
            array = new float[arraySize];
        }
    
        public void accessArray() {
            // I want to access the array from this method.
            float first = array[0];
        }
    }
    
    • You pass the array as parameter to the method (resp. the initializeArray method should return an array)
    public class Arrays {
    
        public static void main(String[] args) {
            int arraySize = 2;
            float[] array = initializeArray(arraySize);
            accessArray(array);
        }
    
        public static float[] initializeArray(int size) {
            return new float[size];
        }
    
        public static void accessArray(float[] floats) {
            // I want to access the array from this method.
            float first = floats[0];
        }
    }
    

提交回复
热议问题