2

Henlo, Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());. But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.

All the code that is meant to run should be inside the main method in Step1.java

Here are the 3 classes used for the code (ignore comments they are just notes for me):

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;
    }

}
lczapski
  • 3,644
  • 3
  • 10
  • 26
yolotwice
  • 13
  • 2
  • I suggest you try to look the web for Java user input, here is a good example: https://www.w3schools.com/java/java_user_input.asp – Coreggon Apr 14 '20 at 12:02
  • I've had a look at this but the issue is that this only shows how to store inputs as a single variable, not inside an object that holds an array of values. – yolotwice Apr 14 '20 at 12:06
  • 1
    HINT: you can use _variables_ as arguments to a `new` expression. Does that give you some ideas? – Kevin Anderson Apr 14 '20 at 12:08

2 Answers2

1

Some of the improvements required in your code are as follows:

  1. Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
  2. You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
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)

Given below is a sample code incorporating the improvements mentioned above:

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());
    }
}

A sample run:

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]
halfer
  • 18,701
  • 13
  • 79
  • 158
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • Thanks for the detailed explanation. I don't require to do any error checking in this particular piece of work but this will undoubtedly come in handy down the line in any future programming questions/work. I can see you are 'hiding the mechanism', usually I would do something like: ```public int getIntInput(String prompt) { Scanner input = new Scanner(System.in); display(prompt); return input.nextInt(); }``` but this is a lot better :) – yolotwice Apr 15 '20 at 12:19
0

So as suggested I tried to do the following:

    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();

}

Got it working but not sure if this is the most efficient way to do so??

yolotwice
  • 13
  • 2