Andrew Harris
Andrew Harris

Reputation: 416

changing the size of an array from a method in java

I have a 2D array and I want to make the size of the array the same as the number of appointments. The number of appointments is found in another class with this line

numOfAppointments = DB.numOfAppointmentsByUser(loggedInUserID);

And I declare the array at the top of the program so it is accessible from the whole program, this is that:

String[][] data = new String[numOfAppointments][2];

But I cant call the numOfAppointments above the data array because it isn't in a method and gives this error: error: <identifier> expected and if I call the numOfAppointment in a method then I will need to declare the data array in that method so that I can use the value from numOfAppointments as the size in the array.

How can I make it so that I can declare the array at the top of the program so it is accessible from all methods but at the same time call the numOfAppointments variable so that I can create the size of the array.

I have tried placing them both in a constructor like this:

numOfAppointments = DB.numOfAppointmentsByUser(loggedInUserID);

public String[][] data = new String[numOfAppointments][2];

I tried to make the array public in the constructor instead but it gives the error illegal start of expression and If I remove the public then the data array isn't accessible from any other method since it isn't public and is a child of that method. Thanks for any help.

Upvotes: 1

Views: 46

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

You need to move the following declaration outside of the constructor to make it available globally!

public String[][] data;

public Constructor(...) {
    int numOfAppointments = DB.numOfAppointmentsByUser(loggedInUserID);

    data = new String[numOfAppointments][2];
}

Upvotes: 3

Related Questions