I’m making an app for an ice cream shop where I need at some point to know how many ice cream from a specific flavor were sold. I have to write the flavor of the ice cream when I add it to the stock, so the ArrayList
that contains the flavor is initially empty. Then I need another ArrayList
which is going to store the number of times that flavor is sold. I need to do it with two ArrayList
s because I don’t understand HashMap
s yet.
IceCream newIceCream = new IceCream(); Integer id = Console.readInt("Id: "); String name = Console.readString("Ice cream name: "); Float price = (float)Console.readDouble("Price: "); String flavour = Console.readString("Flavour: "); newIceCream.setId(id); newIceCream.setNome(name); newIceCream.setPreco(price); newIceCream.setSabor(flavour); iceCreamStock.add(newIceCream);
This is how I create the ice cream.
Integer sellIceCream = Console.readInt("Which ice cream to sell? (id)"); boolean iceCreamExists = false; for (int i = 0; i < iceCreamStock.size() && iceCreamExists == false; i++) { if (iceCreamStock.get(i).getId() == sellIceCream) { iceCreamExists = true; } if (iceCreamExists == true) { soldIceCream.add(iceCreamStock.get(i)); iceCreamStock.remove(i); salesCounter++; System.out.println("Ice cream sold."); } } if (iceCreamExists == false) { System.out.println("Ice cream not found"); }
This is how I sell it. I know I have to work somewhere in these two parts of the program, just can’t figure out how.
Advertisement
Answer
I suggest you use array-indexing to store the relationship between the arrays.
flavourList = List<String> soldList = List<Integer> //initally all 0's
Whenever you add the icecream to the stock, check if the flavour of the ice-cream already exist in the array, if not add the flavour of the ice-cream into the flavourList at the end of the list.
if flavourList.indexOf("flavour") < 0: flavourList.add("flavour")
Now if the flavour is already present in the array, find the index and go to the same index in the soldList array and increment the current value by 1.
indexOfFlavour = flavourList.indexOf("flavour") soldList.set(indexOfFlavour, soldList.get(indexOfFlavour) + 1)