Accessing arrays with methods

后端 未结 4 1986
旧时难觅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条回答
  •  -上瘾入骨i
    2021-01-24 02:44

    This is done thusly

    public class myClass{
      int arraysize = 2;
      float[] myArray; // Declare array
    
      public myClass(){
        myArray = new float[arraySize]; // initialize array 
      }
    
      public float[] accessArray(){
        return myArray;
      }
    }
    

    The array declaration must not be done inside the class methods. Variable declaration done inside a method limits it's scope of a variable to the method. (i.e you can't use it anywhere else).

    The array is then instantiated in a constructor. A constructor is a special function that is run when a class is instantiated. Constructor are used to instantiated a class's variables Constructors have the same name as their class and must not specify a return type (so no public int or public void just public)

    Next you need to change the return type of the accessArray method. A return type of void states that the method isn't going to return anything. Change it to float[] Then your accessArray method need only return the array variable.

    EDIT: The "return myArray;" line of code gives a reference to the array to what ever called the function (Not a copy of the array, the actual array, a quick of Java is that it always does this except when returning primitive data types where it returns a copy)

    If you want accessArray() to set floats in the array instead of returning the array it should be implmented like this.

    public void accessArray(int index, float value){
      myArray[index] = value;
    }
    

提交回复
热议问题