1

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.

1
  • What's the purpose of static word? :) Commented Nov 12, 2017 at 20:40

1 Answer 1

3

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

wow that was so simple, been trying to solve it for ages. That did it, thanks a lot :)
a constructor should only assign values to member variables. It should not call methods in other classes and/or objects! Therefore the number of appointments should be passed as constructor parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.