Issue
I have a Airport class where I built the airport object. Now, I am trying to put different objects in the same array but without changing the object name every single time. The problem is that my program will only get the last object instead of getting all of them. ''' public class Main {
public static void main(String[] args)
{
ArrayList <Airport> myAl = new ArrayList();
Airport obj = new Airport();
int i = -1;
obj.setValues(++i, "Wright-Patterson Air Force Base", "OH", 39.819527, -84.067406, 0);
myAl.add(obj);
obj.setValues(++i, "John F. Kennedy International Airport", "NY",40.641766 , -73.780968,0);
myAl.add(obj);
obj.setValues(++i, "Charlotte Douglas International Airport", "NC", 35.213890, -80.943054, 0);
myAl.add(obj);
obj.setValues(++i, "O’Hare International Airport", " IL", 41.978611, -87.904724, 0);
myAl.add(obj);
obj.setValues(++i, "Tucson International Airport", "AZ", 32.116112, -110.941109, 0);
myAl.add(obj);
Airport xx = new Airport();
for(i =0; i<myAl.size();i++)
{
xx = myAl.get(i);
System.out.print(xx.getId() +" " + xx.getFullName()+"\n");
}
}}
''' Output
4 Tucson International Airport AZ
4 Tucson International Airport AZ
4 Tucson International Airport AZ
4 Tucson International Airport AZ
4 Tucson International Airport AZ
Solution
Create a new Object first
ArrayList <Airport> myAl = new ArrayList();
Airport obj = new Airport();
int i = -1;
obj.setValues(++i, "Wright-Patterson Air Force Base", "OH", 39.819527, -84.067406, 0);
myAl.add(obj);
obj = new Airport();
obj.setValues(++i, "John F. Kennedy International Airport", "NY",40.641766 , -73.780968,0);
myAl.add(obj);
obj = new Airport();
obj.setValues(++i, "Charlotte Douglas International Airport", "NC", 35.213890, -80.943054, 0);
myAl.add(obj);
obj = new Airport();
obj.setValues(++i, "O’Hare International Airport", " IL", 41.978611, -87.904724, 0);
myAl.add(obj);
// etc
Answered By - Scary Wombat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.