Accessing arrays with methods

后端 未结 4 2035
旧时难觅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:44

    Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html

    You can declare the array at class level then it is accessible in all methods.

        public class Arrays {
        int arraysize = 2;
        private float[] array = null;
    
        public void initializeArray() {
            array = new float[arraySize]; // Declare array
        }
    
        public void accessArray() {
            // access array here.
        }
    }
    

    Or You can pass the variables in method.

        public class Arrays {
        int arraysize = 2;
    
        public void initializeArray() {
            float[] array = new float[arraySize]; // Declare array
            accessArray(array);
        }
    
        public void accessArray(float[] array) {
            // access array here.
        }
    }
    

    Given the amount of information, I have from question, approach 1 seems better than 2.

提交回复
热议问题