【发布时间】:2020-07-29 16:45:42
【问题描述】:
亨洛,
我的问题是我必须使用两个不同的构造函数创建两个对象:
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
对于第一个,我用这段代码 sn-p 实现了它:
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size of SmartHome: ");
int size = myObj.nextInt();
SmartHome firstSmartHomeObject = new SmartHome(size);
for(int i=0; i<size;i++) {
System.out.println("\nName: ");
String name = myObj.next();
System.out.println("\nLocation: ");
double location = myObj.nextDouble();
System.out.println("\nIs on?: ");
boolean switchedOn = myObj.nextBoolean();
firstSmartHomeObject.insertDevice(name, location, switchedOn);
}
第二个 insertDevice() 接受SmartDevice dev
我不知道该怎么做。我尝试的是在循环结束时执行SmartDevice dvc+(i) = new SmartDevice(name, location, switchedOn);,但不知道如何创建 dvc1/dvc2/dvc3 等...,甚至不确定这是否是解决此问题的正确方法: (
【问题讨论】:
-
您不必在循环的每次迭代中创建一个新变量(具有不同的名称)。只需调用它
dvc就可以了。 -
使用工厂设计模式
-
@sri OP 正在学习语言/编程基础知识,向他扔设计模式是个坏主意。
-
所以在循环结束时我应该有:
SmartDevice dvc = new SmartDevice(name, location, switchedOn);secondSmartHomeObject.insertDevice(dvc);? -
@Amongalen 我可以看看工厂设计模式,因为我在大学学习的第一年,在过去的几周里,我们只了解了 COMPOSITION、EXTENDS、CONSTRUCTORS、SUPERCLASSES。无论如何,我可能不得不在不久的将来学习“工厂设计模式”。