how do you write a loop that will continuosly create a new instance of an object
ID: 3628179 • Letter: H
Question
how do you write a loop that will continuosly create a new instance of an object without overwriting the previous instance while loading those instances to an object array?Dollar [] d = new Dollar [5];
Dollar d1 = new Dollar();
System.out.println(d1.representation());
Dollar d2 = new Dollar("Washington", "1");
System.out.println(d2.representation());
Dollar d3 = new Dollar("Jackson", "White House", "20");
System.out.println(d3.specificRepresentation());
Dollar d4 = new Dollar ("Lincoln", "Lincoln Memorial","5");
System.out.println(d4.generalRepresentation());
Dollar d5 = new Dollar ("Jefferson","Declaration of independence","2");
System.out.println(d5.specificRepresentation());
System.out.println("");
d [0] = d1;
d [1] = d2;
d [2] = d3;
d [3] = d4;
d [4] = d5;
Explanation / Answer
Dollar[] d = new Dollar[5];
for(int i = 0; i < 5; i++)
{
Dollar dTemp = new Dollar();
d[i] = dTemp;
}
After this loop you will have created 5 objects of Dollar and have added it to d.
You can then access it's properties with d[1].Something
Or whatever you need to do with them.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.