Accessing arrays with methods

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

    You need to move your declaration to make it a member, otherwise it will go out of scope once the initializeArray call ends. Then you can access the array from both methods. Try this:

    public class Arrays{
       float[] array;
       int arraysize = 2;
    
       public void initializeArray(){
          array = new float[arraySize];   // Declare array  
       }
    
       public void accessArray(){
          array[0] = 1.0f;
       }
     }
    

提交回复
热议问题