I am currently working through Objects module over on Hyperskills.org. One of the coding challenges is to create five Units, three Knights, one General, one Doctor. We are given the class definition for each object and each object has a constructor that sets one String field.
I took the prompt and just instantiated x-number of X-class as asked.
public static void createArmy(){
Unit unit1 = new Unit("U1");
Unit unit2 = new Unit("U2");
Unit unit3 = new Unit("U3");
Unit unit4 = new Unit("U4");
Unit unit5 = new Unit("U5");
Knight knight1 = new Knight("K1");
Knight knight2 = new Knight("K2");
Knight knight3 = new Knight("K3");
General general1 = new General("G1");
Doctor doctor1 = new Doctor("D1");
}
The compiler accepts my answer but it says, "Correct, but can be improved."
Please and thank you: How else can this code be improved?
You can improve it by putting the units and stuff into an array and using for loops. Also adding some parameters would make calling this function easier later on. ex:
public static void createArmy(int units, int knights, int generals, int doctors){
Unit unit = new Unit[units];
Knight knight = new Knights[knights];
General general = new Generals[generals];
Doctor doctor = new Doctors[doctors];
for(int x = 0; x < units;x++){
unit[x] = new Unit("U"+(x+1));
}
for(int x = 0; x < knights;x++){
knight[x] = new Knight("K"+(x+1));
}
for(int x = 0; x < generals;x++){
general[x] = new General("G"+(x+1));
}
for(int x = 0; x < doctors;x++){
doctor[x] = new Doctor("D"+(x+1));
}
}