【问题标题】:String Manipulation ? and OOP issue JAVA字符串操作?和 OOP 问题 JAVA
【发布时间】: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。无论如何,我可能不得不在不久的将来学习“工厂设计模式”。

标签: java arrays string oop


【解决方案1】:

应该这样做::s

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2014-03-21
    • 1970-01-01
    • 2011-11-09
    • 2020-08-31
    相关资源
    最近更新 更多