有没有更简洁的方法来实例化对象 A 的 5 个、对象 B 的 3 个、对象 C 的 1 个、对象 D 的 1 个,都在一个方法中?
Is there a more concise way to instantiate 5 of object-A, 3 of object-B, 1 of object-C, 1 of object-D, all inside one method?
我目前正在 Hyperskills.org 上研究对象模块。编码挑战之一是创建五个单位,三个骑士,一个将军,一个博士。我们为每个对象提供了 class 定义,并且每个对象都有一个构造函数来设置一个 String 字段。
我接受了提示,并按照要求实例化了 X-class 的 x-number。
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");
}
编译器接受了我的回答,但它说,"Correct, but can be improved."
拜托,谢谢:此代码还能如何改进?
您可以通过将单位和内容放入数组并使用 for 循环来改进它。另外添加一些参数将使以后调用此函数更容易。例如:
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));
}
}
我目前正在 Hyperskills.org 上研究对象模块。编码挑战之一是创建五个单位,三个骑士,一个将军,一个博士。我们为每个对象提供了 class 定义,并且每个对象都有一个构造函数来设置一个 String 字段。
我接受了提示,并按照要求实例化了 X-class 的 x-number。
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");
}
编译器接受了我的回答,但它说,"Correct, but can be improved."
拜托,谢谢:此代码还能如何改进?
您可以通过将单位和内容放入数组并使用 for 循环来改进它。另外添加一些参数将使以后调用此函数更容易。例如:
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));
}
}