so this is a rather complicated problem for me but I will try to explain best I can -
I have a class called Survey with an:
ArrayList<Question> questions = new ArrayList<Question>();
The list is where I store all the questions belonging to a survey. I am trying to iterate over this list and display these questions.
Here is the tricky part. I have a Main class that uses an instance of Survey to call it's menu methods, and an instance of Survey in a Question class where the current question is being added to the ArrayList.
When I print out:
survey.questions.size()
in my Questions class, after adding one question I get "1".
However when I print out the size in my Survey class, I got "0".
I believe the issue is because Main is using a separate instance of Survey to iterate over the question list than the instance in which I'm adding the questions, in my Question class.
I will try to clear any confusion!
public class Survey {
public ArrayList<Question> questions = new ArrayList<Question>();
// Iterate over questions List
public void displayQuestions() {
int numberCount = 1;
int optionCount = 1;
System.out.println(questions.size()); // PRINTS 0
for (int i = 0; i < questions.size(); i++) {
System.out.print("Question" + numberCount + ") ");
System.out.println(questions.get(i).prompt);
for(int j = 0; j < questions.get(i).options.size(); j++) {
System.out.print(optionCount + ". ");
System.out.println(questions.get(i).options.get(j));
}
}
}
public class Main {
private static Survey survey = new Survey();
// After selecting "Display Survey" menu option
survey.displayQuestions();
public class Question {
protected Survey survey = new Survey();
// After finishing making the question
survey.questions.add(this);
System.out.println(survey.questions.size()); // PRINTS 1
You've got more than one Survey instance, and one has one question added to it, while the other in main has no questions. That's it.
Solution: use only one instance of Survey, and pass it if needed to where it is needed, but don't create a new instance and expect it to hold the same state as other instances because that's not how Java works. Note that Question should most definitely not create an instance of Survey. It can add itself to an existing instance, but it makes no sense for it to create an instance de novo.
Edit
You state in comment:
This is what I thought! I'm very amateur and im trying to stick to good design. Both
survey.displayQuestions()
andsurvey.questions.add(this)
need survey objects to call those methods but I have them in separate classes. I'm not sure how to only use one.
My own inclination is to have the Question class be ignorant of Survey, in other words, it should not hold a Survey instance nor call any of its methods, since it really doesn't need to know about survey, and your goal in coding OOP programs is to minimize connections. Instead whatever class that creates Question instances, have that place the Question into the Survey object.