Using user input to create a new object [JAVA]

给你一囗甜甜゛ 提交于 2019-12-01 10:32:31
Ankush soni

With the limit information provided by you I try to solve the issue:

  1. I am not adding any attributes to Desktop and Laptop class, overriding toString Method in both the Classes i.e.

public class Laptop {
    public String toString() {
        return "Laptop [getClass()=" + getClass() + ", hashCode()="
                + hashCode() + ", toString()=" + super.toString() + "]";
    }
}

public class Desktop {
    public String toString() {
        return "Desktop [getClass()=" + getClass() + ", hashCode()="
                + hashCode() + ", toString()=" + super.toString() + "]";
    }
}

Your Main method look like:

public static void main (String args[]) 
    {
        String input;
        Scanner scanner = new Scanner(System.in);
        List<Object> listOfObject = new ArrayList<>();
        do
        {
            System.out.println("Computer Menu");  
            System.out.println("1. Add a new Desktop Information");
            System.out.println("2. Add a new Laptop Information");
            System.out.println("3. Display all Computer Information");
            System.out.println("4. Quit");

            System.out.print("Please enter either 1 to 4: "); 
            input =(scanner.nextLine());
            if (input.equals("1")){
                Desktop desktop1 = new Desktop();
                listOfObject.add(desktop1);
            }else if (input.equals("2")){
                Laptop laptop1 = new Laptop();
                listOfObject.add(laptop1);
             }else if(input.equals("3")){
                 for(Object obj : listOfObject){
                     if(obj instanceof Desktop){
                        Desktop d1 = (Desktop)obj;
                        System.out.println(d1.toString());
                     }else if(obj instanceof Laptop){
                         Laptop l1 = (Laptop)obj;
                         System.out.println(l1.toString());
                     }
                 }
             }
        }while(!input.equals("4"));
    }

Assuming you have a class/interface named Computer from which Laptop and Desktop extend.

1) Add a list to store Computer instances.

List<Computer> computers = new ArrayList<Computer>()

2) Make actions "1" and "2" add to that list, e.g.

computers.add(desktop1);

3) Make action "3" print out the list. This assumes you've implemented toString()

for (Computer computer : computers) {
   System.out.println(computer);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!