简体   繁体   中英

method to add objects to ArrayList using user input

Can't take my head around the following: There are 2 classes - "Item", where attributes (Name, Price) and constructors are set, and main "Store". In the last one - Arraylist, which fills up with Items depending on user input. The code works.

Here is the question: Is there any way to put all from the main class, apart from "ArrayList listOfItems=new ArrayList();" line into a method "addItem()" and then just call the method? I do not know how to do it. Tried a lot.

Thank you

package store;

import java.util.ArrayList;
import java.util.Scanner;

public class Store extends Item {

public static void main(String[] args) {        

   ArrayList<Item> listOfItems=new ArrayList<Item>();

    for(int i=0;i<2;i++){

        System.out.println("ENTER NAME");
        Scanner addName=new Scanner (System.in);
        String name=(addName.nextLine());

        System.out.println("ENTER PRICE");
        Scanner addPrice=new Scanner (System.in);
        double price=(addPrice.nextDouble());

        listOfItems.add(new Item(name,price));
    }
    for(Item list:listOfItems){
        System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
    }
  }
}

This will work for you:

package store;

import java.util.ArrayList;
import java.util.Scanner;

public class Store {
    private static class Item {
        private String name;
        private double price;

        public Item(String name, double price) {
            this.name = name;
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }
    }

    public static void main(String[] args) {
        ArrayList<Item> listOfItems = new ArrayList<Item>();
        addItem(listOfItems);
    }

    private static void addItem(ArrayList<Item> listOfItems) {
        for (int i = 0; i < 2; i++) {
            System.out.println("ENTER NAME");
            Scanner addName = new Scanner(System.in);
            String name = (addName.nextLine());

            System.out.println("ENTER PRICE");
            Scanner addPrice = new Scanner(System.in);
            double price = (addPrice.nextDouble());

            listOfItems.add(new Item(name, price));
        }
        for (Item list : listOfItems) {
            System.out.println("NAME " + list.getName() + ", PRICE " + list.getPrice());
        }
    }
}

I defined the class Item separately to make it compiling. Also I removed the extends Item from the store, because it is not needed.

I don't know exactly if this is what you are looking for, but you may try the following solution:

public class Store extends Item {

public static void main(String[] args) {

    ArrayList<Item> listOfItems=new ArrayList<Item>();

    addItem(listOfItems);

    for(Item list:listOfItems){
        System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
    }

}

private static void addItem(ArrayList<Item> li) {

    for(int i=0;i<2;i++){

        System.out.println("ENTER NAME");
        Scanner addName=new Scanner (System.in);
        String name=(addName.nextLine());

        System.out.println("ENTER PRICE");
        Scanner addPrice=new Scanner (System.in);
        double price=(addPrice.nextDouble());

        li.add(new Item(name,price));
    }

}

}

You maybe also try to declare the ArrayList outside the main:

public class Store extends Item {

private static ArrayList<Item> listOfItems;

public static void main(String[] args) {

    listOfItems=new ArrayList<Item>();

    addItem();

    for(Item list:listOfItems){
        System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
    }

}

private static void addItem() {

    for(int i=0;i<2;i++){

        System.out.println("ENTER NAME");
        Scanner addName=new Scanner (System.in);
        String name=(addName.nextLine());

        System.out.println("ENTER PRICE");
        Scanner addPrice=new Scanner (System.in);
        double price=(addPrice.nextDouble());

        listOfItems.add(new Item(name,price));
    }

}

}

Let me know if you need further help! :)

You could use a better Oriented Object approach to solve your problem.

Store extends Items this has not sense. The store contains items, so you only need a variable like your listOfItems for save all the items of the store.

Your public class Store is a good candidate to use the Singleton Pattern .

About the construction of your listOfItems : When a List is enough, then simply you should use just a List. Also, java 7 provide the type inference for generic instance creation.

From The Java SE Documentation : You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

So, you should use List<Item> listOfItems = new ArrayList<>() instead of ArrayList<Item> listOfItems = new ArrayList<Item>()

Each time that you use a Scanner you should close it.

The Singleton:

public class Store {
private static final Store INSTANCE = new Store();
private List<Item> listOfItems = new ArrayList<>();

private Store() {
    // Private Constructor
    // will prevent the instantiation of this class directly
}

public static Store getInstance() {
    return INSTANCE;
}

public void addItems(List<Item> newlistOfItems) {
    listOfItems.addAll(newlistOfItems);
}

public String printListOfItems() {
    StringBuilder sb = new StringBuilder();
    for (Item item : listOfItems) {
        sb.append(" [NAME : " + item.getName() + ", PRICE : " +  item.getPrice() + "]");
    }
    return sb.toString();
}

}

The POJO Item class

public class Item {
    private String name;
    private double price;

    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

The service interface for the management of items :

public interface ItemManagerService {
    List<Item> createListOfItems();
}

The implementation:

   public class ItemManagerServiceImpl implements ItemManagerService {
    @Override
    public List<Item> createListOfItems() {
        List<Item> newListOfItems = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        try {
            do {
                System.out.println("ENTER NAME");
                String name = scanner.nextLine();

                System.out.println("ENTER PRICE");
                while (!scanner.hasNextDouble()) {
                    System.out.print("You must enter a valid number! Try again: ");
                    scanner.next();
                }

                double price = scanner.nextDouble();
                Item item = new Item(name, price);
                newListOfItems.add(item);

                System.out.println("Continue?[Y/N]");
                scanner.nextLine();
            } while (scanner.nextLine().equalsIgnoreCase("y"));
        } finally {
            scanner.close();
        }
        return newListOfItems;
    }
}

A simple test :

public class MainApp {

    public static void main(String[] args) {
        ItemManagerService itemManagerService = new ItemManagerServiceImpl();
        List<Item> newlistOfItems = itemManagerService.createListOfItems();

        Store.getInstance().addItems(newlistOfItems);
        System.out.println(Store.getInstance().printListOfItems());
    }
}

The console output:

ENTER NAME
table
ENTER PRICE
12
Continue?[Y/N]
y
ENTER NAME
car
ENTER PRICE
50,8
Continue?[Y/N]
n
 [NAME : table, PRICE : 12.0] [NAME : car, PRICE : 50.8]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM