I'm minoring in computer science at university, and need to write a program with three components:
- A "Circle" class that defines methods for creating and working with a Circle object that has a radius and color as defined attributes in the object.
- A "CircleMgr" class that manages an array of circle objects.
- A "CircleApp" class that produces output for the program.
An issue I'm having (which is causing a runtime error) has been identified by my professor as lying inside the CircleApp class at line 53, which is a for loop iterating through the list--the code is as follows*:
for(int i = 0; i < mainList.length; i ){
System.out.println("Circle " i);
System.out.println(mainList[i].getRadius());
System.out.println(mainList[i].getColor());
}
Earlier in the program, I load the list created and managed by CircleMgr into mainList, which is contained in CircleApp. According to my professor, I need to iterate through only the objects that have been loaded into mainList (which will never be completely filled because we were told to create the object array at a size much larger than what the input file takes in). Unfortunately, I'm not certain how I could iterate through the array in a different manner; is anyone able to provide guidance to this effect?
*(the println statements are there to ensure that the output is correct before I format it, once I am able to move past the runtime error and actually produce output).
CodePudding user response:
You need a count of how many things are stored in the array.
Then, use the count in the loop condition as below.
for(int i = 0; i < count; i ){
System.out.println("Circle " i);
System.out.println(mainList[i].getRadius());
System.out.println(mainList[i].getColor());
}
CodePudding user response:
If your array can never be full, then you can stop iterating when you reach a null item.
for(int i = 0; mainList[i] != null; i ){
System.out.println("Circle " i);
System.out.println(mainList[i].getRadius());
System.out.println(mainList[i].getColor());
}
Later in your studies, you will learn about Lists, which can grow and shrink with your data.