字符串操作?面向对象的JAVA问题

字符串操作?面向对象的JAVA问题,java,arrays,string,oop,Java,Arrays,String,Oop,亨洛 我的问题是,我必须使用两个不同的构造函数创建两个对象: public SmartHome(int size) { smrtDev = new SmartDevice[size]; } public SmartHome(SmartDevice[] values) { smrtDev = values; } 对于第一个,我通过以下代码片段实现了这一点: Scanner myObj = new Scanner(System.in);

亨洛

我的问题是,我必须使用两个不同的构造函数创建两个对象:

public SmartHome(int size) {
       smrtDev = new SmartDevice[size];
   }

public SmartHome(SmartDevice[] values) {
       smrtDev = values;
   }
对于第一个,我通过以下代码片段实现了这一点:

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);
        }
Scanner myObj=新扫描仪(System.in);
System.out.println(“输入SmartHome的大小:”);
int size=myObj.nextInt();
SmartHome firstSmartHomeObject=新的SmartHome(大小);
对于(int i=0;i应该做的事::s

SmartDevice dvc = new SmartDevice(name, location, switchedOn); secondSmartHomeObject.insertDevice(dvc);

您不必在循环的每次迭代中创建一个新变量(使用不同的名称)。只需调用它
dvc
,就可以了。使用工厂设计pattern@sriOP正在学习语言/编程基础知识,在我看来,向他扔设计模式是个坏主意。因此,在循环结束时,我应该有:
SmartDevice dvc=new SmartDevice(名称、位置、开关打开);
secondSmartHomeObject.insertDevice(dvc);
?@Amongalen我可以看看工厂设计模式,因为我在大学学习的第一年,在过去的几周里,我们只学习了构图、扩展、构造函数和超类。无论如何,我可能在不久的将来必须学习“工厂设计模式”。