如何获取用户输入并存储在自定义对象中?爪哇

时间:2020-04-14 11:47:06

标签: java class oop

Henlo, 基本上,即时通讯试图做的是获取用户输入并将其存储在自定义对象中,但是我不知道该如何处理。我创建了一个loadDataFromConfig()方法?,它在创建对象SmartHome app = new SmartHome(loadDataFromConfig());时工作正常。 但是我完全迷住了如何获取用户输入并将其以以下格式存储:dev[0] = new SmartDevice("device 1",1.3,true);

所有要运行的代码都应位于Step1.java

的main方法中

这里是用于代码的3个类(忽略注释,它们只是对我的注释):

package SmartHomeApp;

public class SmartDevice {
    private String name;
    private double location;
    private boolean switchedOn;

    public SmartDevice(String val1, double val2, boolean val3) {
        setName(val1);
        setLocation(val2);
        setSwitchedOn(val3);
    }

    //YOU CANT ACCESS the 'private classes' so you need to GET them
    public void setName(String value) {name = value;}
    public void setLocation(double value) {location = value;}
    public void setSwitchedOn(boolean value) {switchedOn = value;}

    public String getName() {return name;}
    public double getLocation() {return location;}
    public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;

public class SmartHome 
     {

    private SmartDevice[] smrtDev;

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

    public SmartHome(SmartDevice[] values) {
        smrtDev = values;
    }

    public int size() {return smrtDev.length;}

    // can't do toString() for some reason??
    public void ToString() {

            for(int i=0; i<size();i++) 
            {
                if(smrtDev[i] != null ){ 
                System.out.println("----------");
                System.out.println("-DEVICE "+(i+1)+"-");
                System.out.println("----------");
                System.out.println("Name:            "+smrtDev[i].getName());
                System.out.println("Location:        "+smrtDev[i].getLocation());
                System.out.println("Switched On:     "+smrtDev[i].getSwitchedOn());

            }
        }
    }
     }
package SmartHomeApp;
import java.util.*;


public class Step1 {

    public static void main(String args[]) {
        SmartHome app = new SmartHome(loadDataFromConfig());
        app.ToString();

    }
    public static SmartDevice[] loadDataFromConfig() 
    {
        SmartDevice[] dev = new SmartDevice[20];

        dev[0] = new SmartDevice("device 1",1.3,true);
        dev[1] = new SmartDevice("device 2",2.3,false);
        dev[2] = new SmartDevice("device 3",3.3,true);
        dev[4] = new SmartDevice("device 5",4.3,false);
        dev[19] = new SmartDevice("device 20",5.3,false);


        return dev;
    }

}

2 个答案:

答案 0 :(得分:1)

your code中需要进行的一些改进如下:

  1. 关注Java naming conventions,例如ToString()应该是toString()。检查this,以了解有关toString()的更多信息。大多数IDE(例如eclipse)都提供了一种功能,可在单击按钮时生成toString()方法。无论以何种方式(手动或在IDE的帮助下)生成它,它都必须返回String
  2. 您应该放弃使用next()nextInt()nextDouble()等,而改为使用nextLine()。检查this了解更多信息。为了让您了解next()nextDouble()可能引起的问题,请尝试输入一个带有空格的名称,例如
Enter size: 
2
Name: 
Light Amplification by Stimulated Emission of Radiation
Location: 
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at Main.main(Main.java:83)

以下是结合了上述改进的示例代码:

import java.util.Scanner;

class SmartDevice {
    private String name;
    private double location;
    private boolean switchedOn;

    public SmartDevice(String val1, double val2, boolean val3) {
        setName(val1);
        setLocation(val2);
        setSwitchedOn(val3);
    }

    // YOU CANT ACCESS the 'private classes' so you need to GET them
    public void setName(String value) {
        name = value;
    }

    public void setLocation(double value) {
        location = value;
    }

    public void setSwitchedOn(boolean value) {
        switchedOn = value;
    }

    public String getName() {
        return name;
    }

    public double getLocation() {
        return location;
    }

    public boolean getSwitchedOn() {
        return switchedOn;
    }

    @Override
    public String toString() {
        return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
    }
}

class SmartHome {

    private SmartDevice[] smrtDev;

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

    public SmartHome(SmartDevice[] values) {
        smrtDev = values;
    }

    public int size() {
        return smrtDev.length;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (SmartDevice smartDevice : smrtDev) {
            sb.append(smartDevice.toString()).append("\n");
        }
        return sb.toString();
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);
        int size = getPositiveInt(myObj, "Enter size: ");

        SmartDevice[] newList = new SmartDevice[size];

        for (int i = 0; i < newList.length; i++) {
            System.out.print("Name: ");
            String x = myObj.nextLine();
            double y = getFloatingPointNumber(myObj, "Location: ");
            boolean z = getBoolean(myObj, "Is on?: ");
            newList[i] = new SmartDevice(x, y, z);
        }
        SmartHome newDevice = new SmartHome(newList);
        System.out.println(newDevice);
    }

    static int getPositiveInt(Scanner in, String message) {
        boolean valid;
        int n = 0;
        do {
            valid = true;
            System.out.print(message);
            try {
                n = Integer.parseInt(in.nextLine());
                if (n <= 0) {
                    throw new IllegalArgumentException();
                }
            } catch (IllegalArgumentException e) {
                System.out.println("This in not a positive integer. Please try again.");
                valid = false;
            }
        } while (!valid);
        return n;
    }

    static double getFloatingPointNumber(Scanner in, String message) {
        boolean valid;
        double n = 0;
        do {
            valid = true;
            System.out.print(message);
            try {
                n = Double.parseDouble(in.nextLine());
            } catch (NumberFormatException | NullPointerException e) {
                System.out.println("This in not a number. Please try again.");
                valid = false;
            }
        } while (!valid);
        return n;
    }

    static boolean getBoolean(Scanner in, String message) {
        System.out.print(message);
        return Boolean.parseBoolean(in.nextLine());
    }
}

示例运行:

Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]

答案 1 :(得分:0)

因此,按照我的建议,我尝试执行以下操作:

    public static void main(String args[]) {

    Scanner myObj = new Scanner(System.in);

    System.out.println("Enter size: ");
    int size = myObj.nextInt();

    SmartDevice[] newList = new SmartDevice[size];

    for(int i =0; i<newList.length;i++) {
        System.out.println("Name: ");
        String x = myObj.next();
            System.out.println("Location: ");
            double y = myObj.nextDouble();
                System.out.println("Is on?: ");
                boolean z = myObj.nextBoolean();
        newList[i] = new SmartDevice(x,y,z);            

    }
    SmartHome newDevice = new SmartHome(newList);   
    newDevice.ToString();

}

让它正常工作,但不确定这是否是最有效的方法?