implementing a linked list with StockList - java

EDIT: Thanks for the help. My tutor gave me an assignment to do with this code and iv'e put in all of the given code snippets into my code and tried to correct my code. However one thing im stuck on is that the Linked list class has "class, enum, Interface expected". I tried using both the Stock Item and Stock List class in the parameters of Stock Linked List but no luck. Any help would be greatly appreciated
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computercompany;
/**
*
* #author obliv_000
*/
public class StockItem
{
private String itemID;
private String itemDesc;
private double price;
private int quantity;
private int reOrderLevel;
public String getItemID()
{
return itemID;
}
public String getItemDesc()
{
return itemDesc;
}
public double getPrice()
{
return price;
}
public int getQuantity()
{
return quantity;
}
public int getReOrderLevel()
{
return reOrderLevel;
}
public StockItem(String itemsID, String itemsDesc, double p, int quant,
int rol)
{
itemID = itemsID;
itemDesc = itemsDesc;
quantity = quant;
reOrderLevel = rol;
price = p;
}
public void setPrice(double price)
{
this.price = price;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public void setReOrderLevel(int reOrderLevel)
{
this.reOrderLevel = reOrderLevel;
}
public String toString()
{
return "itemID = " + getItemID() + ", itemDesc = " + getItemDesc() +
", price = " + getPrice() + ", quantify = " + getQuantity() +
", reOrderLevel = " + getReOrderLevel();
}
public String format()
{
return "The values for the following variables are:\nItemID: " +
getItemID() + "\nItemDesc: " + getItemDesc() + "\nPrice: " +
getPrice() + "\nQuantify: " + getQuantity() + "\nReOrderLevel: "
+ getReOrderLevel();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computercompany;
/**
*
* #author obliv_000
*/
public interface StockList
{
public StockLinkedList stock = new StockLinkedList();
public void addItem(StockItem item);
public void deleteItem(String itemID);
public void updateItemPrice(String itemID, double price);
public void updateItemQuantity(String itemID, int quantity);
public void updateReOrderLevel(String itemID, int reOrderLevel);
public String formatStockList(String list)
{
list = String.format
("ItemID Description Price Qnty Re-Order Level\n"
+ "****** *********** ***** **** **************\n");
return list;
}
public String formatReOrderList()
{
ListIterator<StockItem> iterf = ItemList.listIterator();
String reReOrderList = FormattedTitle;
while(iterf.hasNext())
{
StockItem temp = iterf.next;
int quant = temp.getQuantity();
int reorder = temp.getReOrderLevel();
if(quant<reorder)
{
formattedReOrder += iterf.next().format() + "\n";
}
}
}
ListIterator listIterator()
{
throw new UnsupportedOperationException("Not yet implemented");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computercompany;
/**
*
* #author obliv_000
*/
public class StockLinkedList<StockList>
{
private StockLinkedList<StockList> prevItem;
private StockItem myItem;
private StockLinkedList<StockList> nextItem;
public StockLinkedList(StockList item)
{
this(null, item, null);
}
public StockLinkedList(StockList item, StockLinkedList<StockList> previous,
StockLinkedList next)
{
myItem = item;
nextItem = next;
prevItem = previous;
}
}
public StockList getMyItem()
{
return myItem;
}
public StockLinkedList<StockList> getNextItem()
{
return nextItem;
}
public StockLinkedList<StockList> getPrevItem()
{
return prevItem;
}
public void setItem(StockList item)
{
myItem = item;
}
public void setPrevItem(StockLinkedList<StockList> previous)
{
prevItem = previous;
}
public void setNextItem(StockLinkedList<StockList> next)
{
nextItem = next;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computercompany;
import static computercompany.StockList.stock;
/**
*
* #author obliv_000
*/
public class StockListCLI
{
private StockList stock = null;
public StockListCLI(StockList stock)
{
}
// Displays main menu and gets valid option from user
public void doMenu()
{
}
// Obtain input for stock list operation
// and invoke operation
private void doAddItem()
{
stockList.add(item);
}
private void doDeleteItem()
{
Iterator<StockItem> itr = stockList.listIterator();
while(itr.hasNext())
{
StockItem item = itr.next();
if(item.getItemID().equals(itemID))
{
itr.remove();
break;
}
}
}
private void doUpdateItemPrice()
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getItemID().equals(itemID))
{
item.setPrice(price);
break;
}
}
}
private void doUpdateItemQuantity()
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getItemID().equals(itemID))
{
item.setReOrderLevel(reOrderLevel);
break;
}
}
}
private void doUpdateReOrderLevel()
{
StockLinkedList itr = stock.listIterator();
while(itr.setNextItem())
{
StockItem item = (StockItem)itr.next();
if(item.getItemID().equals(itemID))
{
item.setQuantity(quantity);
break;
}
}
}
// Display contents of stock list
private void doPrintStockList()
{
}
// Display contents of re-order list
private void doPrintReorderLIst()
{
}
}

Few notes/corrections:
1) don't implement any methods in your interface, use it as contract/ definition of services/method that will have to be provided by classes which implement it
2) think about the requirements for your class/interface - why do you need LinkedList at all? Is the order important?
3) implement all methods in your class

So much wrong in one small code bit it's hard to know where to start.
An interface is something that should only put forward the signatures (return value, method name and parameters) of public methods.
An abstract class is a class that doesn't have a full implementation and can not be allocated it can only be inherited/subclassed.
Not knowing the purpose of this code it's hard to say much more. But assuming you do want an interface to say what can be done to a StockList and several types of implementation of a StockList (one of them being a StockLinkedList) you should have:
interface class StockList - defines possible operation on a stock list
class StockItem - item stored in a stock list
class StockLinkedList - implements StockList interface in a linked list fashion
class StockLinkedListNode - implements each element of the linked list with pointer to data and pointer to next (and previous if a double linked list) StockLinkedListNode
Good Luck!

Related

JOptionPane not displaying all items from ArrayList

I am trying to write a program that will create a food order consisting of food items displayed from a menu. Each item is selected and given a certain quantity. I want to display the items that I select in a JTextField but it has not been working correctly.
There are a few problems that I have ran into and cannot seem to figure out,
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
The following is my are all of my class files.
import java.util.ArrayList;
public class Menu {
private final ArrayList<Item> menu;
public Menu() {
menu = new ArrayList<>();
}
public void addItem(Item item) {
menu.add(item);
}
public Item getItem(int itemNo) {
if (menu.size() > itemNo) {
return menu.get(itemNo);
}
return null;
}
#Override
public String toString() {
for (int i = 0; i < menu.size(); i++) {
return String.format("%s: %s \n",i+1, menu.get(i));
}
return null;
}
}
public class Item {
private final String name;
private final double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return String.format("Name %s # Price $%s", name, price);
}
public boolean equals(Item item) {
return item.name.equals(item.name);
}
}
public class ItemQty {
private final Item item;
private final int quantity;
public ItemQty(Item item, int quantity) {
this.item = item;
this.quantity = quantity;
}
public Item getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
#Override
public String toString() {
return String.format("%s - %s\n", quantity, item);
}
public boolean equals(ItemQty itemQty) {
return itemQty.getItem().equals(itemQty.getItem());
}
}
import java.util.ArrayList;
public class Order {
private final ArrayList<ItemQty> order;
public Order() {
order = new ArrayList<>();
}
public void addToOrder(ItemQty itemQty) {
if (order.contains(itemQty)) {
int amount = itemQty.getQuantity();
amount += 1;
}
else
order.add(itemQty);
}
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
#Override
public String toString() {
String str = "";
for (int index = 0; index < order.size(); index++) {
str += order.get(index).toString() + "\n\n";
}
return str;
}
}
Any help or critiques would be appreciated
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
This is due to the fact that you're returning the value of sum only after the first iteration of your loop
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
Something like...
public double getTotalPrice() {
double sum = 0;
for (Order item : order) {
double price = item.getItem().getPrice();
int quantity = item.getQuantity();
sum += (price * quantity);
}
return sum;
}
would work better
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
Since there is no JOptionPane in your code, it's impossible to know what the issue might be
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
Okay, this is a lot more difficult, because you code doesn't really provide enough support to do it.
There's no way for your code to update the quantity information after the ItemQty is created, you will need to supply a setter of some kind to perform this action (or a add method, to which you pass another ItemQty and it does the job for you)
First, I'd add a new method to ItemQty
public class ItemQty {
//...
public void add(int quantity) {
this.quantity += quantity;
}
}
This just makes it possible to increase the quantity.
Second, I'd change the Order#addToOrder, I'd make it so you had to pass an Item and a quantity to it (other classes don't need to make a ItemQty object in this case). In this method, I'd search for a matching item and either update it or add it to the order.
public class Order {
//...
public void addToOrder(Item item, int quantity) {
List<ItemQty> matches = order.stream().filter((itemQty) -> {
return itemQty.getItem().equals(item);
}).collect(Collectors.toList());
if (matches.size() > 0) {
matches.get(0).add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}
Okay, that might have you scratching your head, it does me, but basically, it's just a fancy pancy way for saying...
public void addToOrder(Item item, int quantity) {
ItemQty match = null;
for (ItemQty check : order) {
if (check.getItem().equals(item)) {
match = check;
break;
}
}
if (match != null) {
match.add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}

can anyone help me with the sorting using compare to in array list?

Hi guys I am making an inventory program and I am having trouble with the stockItem sorting method.which i need to use compareto to solve it.
This is my code so far. Please scroll to the bottom to see what I'm talking about.
public class Inventory {
private ArrayList<StockItem> stock;
public Inventory() {
stock = new ArrayList<StockItem>();
}
public void addStockItem(StockItem item) {
stock.add(item);
}
public int size() {
return stock.size();
}
public String toString() {
String result = "";
for(StockItem item: stock)
result+=item.toString()+"\n";
return result;
}
public boolean isValidIndex(int index) {
return index >=0 && index < stock.size();
}
/**
*
* #param index
* #return null if index is not valid, otherwise
* return item at that index
*/
public StockItem getItem(int index) {
if (index < 0 || index >= this.stock.size())// check if this index exists
return null; // removes the item the from stock and returns it
else
return this.stock.get(index);
}
/**
*
* #param index
* #return null if index is invalid, otherwise remove item at the given
* index and return the removed item.
*/
public StockItem remove(int index) {
if (index < 0 || index >= this.stock.size()) // check if this index exists
return null; // removes the item the from stock and returns it
else
return this.stock.remove(index);
}
/**
* sort, using {#link StockItem#compareTo(StockItem)}
* cannot use built-in sort method from java
*/
public void sort() {
}
I guess that you want to order your items by their sizes. You may use any existing algorithm for sorting such as selection sort, insertion sort or bubble sort. Furthermore, it is possible to use the Java built-in method from Collections module which is much faster and easier to implement. You may use Collections.sort() method given that your class is implementing Comparable interface and its abstract method compareTo(). You can implement comapreTo() method manually or just use Integer class to do so. I used the second approach. I am building a StockItem class with the necessary methods and fields you need to sort. Your code for Inventory should look like this:
import java.util.ArrayList;
import java.util.Collections;
public class Inventory {
private ArrayList<StockItem> stock;
public Inventory() {
stock = new ArrayList<StockItem>();
}
public void addStockItem(StockItem item) {
stock.add(item);
}
public int size() {
return stock.size();
}
public String toString() {
String result = "";
for(StockItem item: stock)
result+=item.toString()+"\n";
return result;
}
public boolean isValidIndex(int index) {
return index >=0 && index < stock.size();
}
/**
*
* #param index
* #return null if index is not valid, otherwise
* return item at that index
*/
public StockItem getItem(int index) {
if (index < 0 || index >= this.stock.size())// check if this index exists
return null; // removes the item the from stock and returns it
else
return this.stock.get(index);
}
/**
*
* #param index
* #return null if index is invalid, otherwise remove item at the given
* index and return the removed item.
*/
public StockItem remove(int index) {
if (index < 0 || index >= this.stock.size()) // check if this index exists
return null; // removes the item the from stock and returns it
else
return this.stock.remove(index);
}
/**
* sort, using {#link StockItem#compareTo(StockItem)}
* cannot use built-in sort method from java
*/
public void sort() {
Collections.sort(stock);
}
}
and your code for StockItem class should be similar to the following:
public class StockItem implements Comparable<StockItem>{
private int size;
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return this.size;
}
public Integer getSizeNonPrimativeInt() {
return new Integer(this.getSize());
}
#Override
public int compareTo(StockItem item) {
return this.getSizeNonPrimativeInt().compareTo(item.getSizeNonPrimativeInt());
}
}
Hope this help ;)
You have not pasted your code for StockItem class. So I assume a sample class below and you can change your code accordingly. Lets assume your StockItem class like below:
class StockItem{
private String itemName;
private double itemPrice;
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
}
You mentioned you cannot use in-built sort() method from Collections, but I guess you might be pointed out you cannot use sort() method just because it sorts not the way you wanted? You need to define a comparator object with your custom sorting criteria and pass it to your in-built sort() method.
public class Inventory {
private ArrayList<StockItem> stock;
//-- your other code segments
static class ListComparator implements Comparator<StockItem>{
#Override
public int compare(StockItem o1, StockItem o2) {
if(o1.getItemName().compareTo(o2.getItemName())>0){
return 1;
}
else if(o1.getItemName().compareTo(o2.getItemName())<0){
return -1;
}
else
return 0;
}
}
public void sort() {
Collections.sort(stock, new ListComparator());
}
}

World of Zuul - adding items using an ArrayList

I am currently trying to improve "World of Zuul" using BlueJ. I am at the point where I have made an Item class and put a few items in there. The next step is to place the items into rooms which I think presents the current problem I am facing: How do you reference or use an ArrayList established in another class? Hopefully if I can understand how that is done, then I may be able to work out how to place a specific item or items in a specific room.
Any help would be appreciated.
Please see my code below:
Itemclass
public Item(String itemDescription, int itemWeight)
{
// initialise instance variables
itemDescription = itemDescription;
itemWeight = itemWeight;
this.list = new ArrayList<Item>();
Item item = new Item(itemDescription, itemWeight);
}
/**
* Name of item
*/
public String getItemDescription()
{
return itemDescription;
}
/**
* Weight of an Item
*/
public int itemWeight()
{
return itemWeight;
}
/**
* Show items
*/
public ArrayList<Item> getItems ()
{
return list;
}
public String getItemString()
{
String returnString = "Item:";
{
returnString += ""+list;
}
return returnString;
}
/**
* Presents name and weight of item
*/
public String toString()
{
return "Item: " + itemDescription + "Weight " + itemWeight;
}
/**
* List of items
*/
public void addItem()
{
list.add(new Item("can of coke",1));
list.add(new Item("bike",6));
list.add(new Item("textbook",4));
list.add(new Item("£20 note",1));
list.add(new Item("stick",2));
list.add(new Item("Theater leaflet",1));
list.add(new Item("mobile phone",2));
}
Room class
public class Room
{
private String description;
private HashMap<String, Room> exits;
public Room(String description)
{
this.description = description;
}
/**
* Define the exits of this room. Every direction either leads
* to another room or is null (no exit there).
* #param north The north exit.
* #param east The east east.
* #param south The south exit.
* #param west The west exit.
*/
public void setExit(String direction, Room neighbor)
{
exits.put(direction, neighbor);
}
public Room getExit(String direction)
{
return exits.get(direction);
}
/**
* #return The description of the room.
*/
public String getDescription()
{
return description;
}
/**
* Return a long description of this room, of the form;
* You are in the kitchen.
* Exits: north west
* #return A description of the room, including exits.
*/
public String getLongDescription()
{
return "You are" + description + "./n" +getExitString();
}
/**
* Return a description of the room's exits,
* for example, "Exits: north west".
* #return A description of the available exits.
*
*/
public String getExitString()
{
String returnString = "Exits:";
Set<String> keys = exits.keySet();
for(String exit :keys) {
returnString += "" + exits;
}
return returnString;
}
}

Java prints only last entry of HashMap when run without debugger

I want my program print all the entries in HashMap, and it does if I run the app in debugger. But if I run it normaly it prints only the last entry :(
Have no idea why it does,
Please help me.
MoneyCounter:
package home.lib;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import home.interfaces.GoodsOper;
import home.interfaces.WalletOper;
import home.interfaces.WastesListOper;
public class MoneyCounter implements WastesListOper, WalletOper, GoodsOper {
private ArrayList<String> wastesPrint = new ArrayList<>();
private Map<GregorianCalendar, Good> wastesMap = new HashMap<GregorianCalendar, Good>();
private Map<String, Good> goodsMap = new HashMap<String, Good>();
private Map<String, Wallet> walletsMap = new HashMap<String, Wallet>();
private Wallet currentWallet;
private Good currentGood;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
/**
* Provides selling (returning) of specified good puts the good
* to the wastesMap by date
* #param goodName
*/
#Override
public void sell(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
putMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Provides buying specified good puts the good you've bought
* to the wastesMap by date
* #param goodName
*/
#Override
public void buy(String goodName) {
// TODO implement the summation of wastes
if(goodsMap.containsKey(goodName)){
takeMoney(goodsMap.get(goodName).getPrice());
wastesMap.put(new GregorianCalendar(), goodsMap.get(goodName));
}
}
/**
* Add a new Wallet to the list if there is no the same one
* #param name
* #param currency
*/
#Override
public void createWallet(String name, String currency) {
walletsMap.putIfAbsent(name, new Wallet(name, currency));
}
/**
* Adds a new Good to the list with specified price
* #param name
* #param price
*/
#Override
public void createGood(String name, int price) {
goodsMap.putIfAbsent(name, new Good(name, price));
}
/**
* Returns array of strings with goods specifications, which
* satisfies the interval [startPrice, endPrice]
* #param startPrice
* #param endPrice
* #return array of strings String[]
*/
#Override
public String[] goodsListToStringByPrice(int startPrice, int endPrice) {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
if (e.getValue().getPrice() >= startPrice && e.getValue().getPrice() <= endPrice) {
goods[i++] = e.getValue().goodToString();
}
}
return goods;
}
/**
* Returns an array of Strings with goods descriptions
* #return array of strings String[]
*/
#Override
public String[] goodsListToString() {
String[] goods = new String[goodsMap.size()];
int i = 0;
for (Map.Entry<String, Good> e : goodsMap.entrySet()) {
goods[i++] = e.getValue().goodToString();
}
return goods;
}
/**
* Replaces old Wallet's name with new one specified if one's name is absent
* #param oldName
* #param newName
*/
public void changeWalletName(String oldName, String newName) {
walletsMap.putIfAbsent(newName, new Wallet(newName, walletsMap.get(oldName)));
walletsMap.remove(oldName);
}
/**
* Returns an array of Strings with wallet descriptions
* #return array of strings String[]
*/
public String[] walletListToString() {
String[] wallets = new String[walletsMap.size()];
int i = 0;
for (Map.Entry<String, Wallet> e : walletsMap.entrySet()) {
wallets[i++] = e.getValue().walletToString();
}
return wallets;
}
/**
* Returns the wallet's money balance by name
* #param walletName
* #return String
*/
public String checkWallet(String walletName) {
return walletsMap.get(walletName).walletToString();
}
/**
* Deletes the wallet, specified by name from wallet list
* #param walletName
*/
#Override
public void delWallet(String walletName) {
walletsMap.remove(walletName);
}
/**
* Deletes the good, specified by name from good list
* #param goodName
*/
#Override
public void delGood(String goodName) {
goodsMap.remove(goodName);
}
/**
* Use this method to put more money to the wallet
* got payment for example
* #param count
*/
#Override
public void putMoney(int count) {
currentWallet.addMoney(count);
}
/**
* Use this method if you need money but not for buying a good
* #param count
*/
#Override
public void takeMoney(int count) {
currentWallet.getMoney(count);
}
/**
* Returns list of all wallets
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToString() {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
array.add(entry.getValue().walletToString());
}
return array;
}
/**
* Returns list of wallets specified by currency
* #param currency
* #return ArrayList
*/
#Override
public ArrayList<String> walletsListToStringByCurrency(String currency) {
ArrayList<String> array = new ArrayList<>();
for (Map.Entry<String, Wallet> entry : walletsMap.entrySet()) {
if (entry.getValue().getCurrency().equals(currency)) {
array.add(entry.getValue().walletToString());
}
}
return array;
}
/**
* Chooses wallet to operate with when you bus, sell, etc.
* #param walletName
*/
#Override
public void chooseTheWallet(String walletName) {
if (walletsMap.containsKey(walletName)) {
this.currentWallet = walletsMap.get(walletName);
}
}
/**
* Returns list of strings of all money wastes you've ever done
* #return ArrayList wastesPrint
*/
#Override
public void wastesListFillUp() {
for(Map.Entry<GregorianCalendar, Good> entry:wastesMap.entrySet()){
this.wastesPrint.add(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Is used for tests
* #throws IOException
*/
public void printAllList() throws IOException {
for (Map.Entry<GregorianCalendar, Good> entry : wastesMap.entrySet()) {
System.out.println(dateFormat.format(entry.getKey().getTime())+" "+entry.getValue().goodToString()+
" "+currentWallet.walletToString());
}
}
/**
* Changes the specified good's price
* #param price
*/
#Override
public void changePrice(int price) {
currentGood.changePrice(price);
}
/**
* Chooses the good for operations
* #param goodName
*/
#Override
public void chooseTheGood(String goodName) {
if (goodsMap.containsKey(goodName)) {
this.currentGood = goodsMap.get(goodName);
}
}
}
Main:
package home.main;
import java.io.IOException;
import home.lib.MoneyCounter;
public class Main {
public static void main(String[] args) throws IOException {
MoneyCounter application = new MoneyCounter();
application.createGood("Snikers", 850);
application.createGood("Хрень какая-то", 1000);
application.createWallet("Основоной счет", "UAH");
application.chooseTheWallet("Основоной счет");
application.buy("Snikers");
application.buy("Хрень какая-то");
application.printAllList();
}
}
Wallet:
package home.lib;
public class Wallet {
// all money is kept
private int moneyCount;
private int debt;
private String currency;
private String name;
// constructor for new Wallet
public Wallet(String walletName, String currencyName) {
this.currency = currencyName;
this.moneyCount = 0;
this.debt = 0;
this.name = walletName;
}
// for renaming Wallet in WalletList
public Wallet(String walletName, Wallet oldWallet) {
this.name = walletName;
this.moneyCount = oldWallet.getMoneyCount();
this.debt = oldWallet.getDebt();
this.currency = oldWallet.getCurrency();
}
// actions with money
public void addMoney(int moneyCount) {
if (this.moneyCount >= 0 && this.debt == 0) {
this.moneyCount += moneyCount;
} else {
moneyCount -= this.debt;
this.debt = 0;
this.moneyCount = moneyCount;
}
}
public void getMoney(int moneyCount) {
if (this.debt == 0 && this.moneyCount > 0 && this.moneyCount >= moneyCount) {
this.moneyCount -= moneyCount;
} else {
moneyCount -= this.moneyCount;
this.moneyCount = 0;
this.debt += moneyCount;
}
}
// getters/setters block
public int getMoneyCount() {
return this.moneyCount;
}
public int getDebt() {
return this.debt;
}
public String getName() {
return this.name;
}
public String getCurrency() {
return this.currency;
}
public String walletToString() {
return this.debt <= 0 ? "("+this.name + " Остаток: " + (double)this.moneyCount/100 + " " + this.currency+")"
: "("+this.name + " Долг: -" + (double)this.debt/100 + " " + this.currency+")";
}
}
Good:
package home.lib;
public class Good {
private int price;
private String name;
public Good(String goodName, int goodPrice) {
this.name = goodName;
this.price = goodPrice;
}
public int getPrice() {
return this.price;
}
public double getPriceInDouble() {
return (double)this.price / 100;
}
public void changePrice(int price) {
this.price = price;
}
public String getName() {
return this.name;
}
public String goodToString() {
return "Товар: " + this.name + " | Цена: " + (double) this.price / 100;
}
}
I've got an answer. I used GregorainCalendar as a HashMap key. So, when I was starting program normaly, it was done in no time. So it was adding different values for ONE key. When you run the program in debugger you can't press next step 10 times in one moment so the time is different, so the keys are different too, so it returns all entries.
Be attentive when use time and all will be Ok :)

How to print out the contents of a HashMap in a certain format?

I'm not entirely sure how I would do this, here is my code:
public class PizzaMenu
{
static Map<String,Pizza> namedPizzas= new HashMap<String,Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
namedPizzas.put(name, pizza);
}
public String printMenu()
{
/*
String menuString="";
for (Every menu item)
{
//Add name of menu item to menuString with carriage return
//Add details of menu item (pizza.getInfo();) to menuString
}
*/
//return menuString
}
}
I would then call System.out.println(PizzaMenu.printMenu()) in another class. The sort of format I'm hoping to achieve is as follows:
/*
* PizzaName
* Details
*
* Next PizzaName in menu
* Details
*
* Next PizzaName in menu
* Details
*
*
*
*/
Am I maybe using the wrong data structure for this type of operation or is there a way of achieving this?
Here is the structure of the Pizza class (apologies for poor formatting):
public class Pizza
{
private double cost;
private Boolean veg;
private PizzaBase base;
private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();
public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
setBase (base);
toppings.add(topping);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
toppings.add(topping3);
}
public double getCost()
{
return cost;
}
public void setCost(double cost)
{
this.cost = cost;
}
public PizzaBase getBase()
{
return base;
}
public void setBase(PizzaBase base)
{
this.base = base;
}
public List<PizzaTopping> getToppings()
{
return this.toppings;
}
public String getToppingsInfo()
{
String toppingInfo = "\n";
PizzaTopping t;
for (int i = 0; i<getToppings().size();i++)
{
t = toppings.get(i);
toppingInfo=toppingInfo+t.getInfo();
}
return toppingInfo;
}
public Boolean getVeg()
{
return veg;
}
public void setVeg(Boolean veg)
{
this.veg = veg;
}
public double calculateCost()
{
PizzaTopping p;
//Loop through all ingredients and add their costs to total cost
for (int i = 0; i<toppings.size();i++)
{
p = toppings.get(i);
cost+=p.getCost();
}
cost+=base.getCost(); //Add pizza base cost to total cost
return cost;
}
//Check if pizza is vegetarian depending upon its ingredients
public Boolean isVeg()
{
Boolean toppingCheck =true;
Boolean baseCheck = true;
PizzaTopping t; //Temporary value used to stored toppings being compared in for loop
//Check each topping and check if it's suitable for vegetarians
for (int i =0; i<toppings.size();i++)
{
while (toppingCheck == true)
{
t = toppings.get(i);
if (t.getVeg()==false)
{
toppingCheck = false;
}
}
}
//Check base to see if it's suitable for vegetarians
if (getBase().getVeg()==false)
{
baseCheck = false;
}
//Return value depending on if all ingredients are suitable for vegetarians
if (toppingCheck == true && baseCheck == true)
{
return true;
}
else return false;
}
public String getInfo()
{
String vegInfo;
if (this.isVeg()==true)
{
vegInfo = "Yes";
}
else vegInfo ="No";
return String.format("Toppings:%s\n"+"Base:\n%s"+"\nTotal Cost:\t£%.2f"+"\nSuitable for vegetarians: %s", getToppingsInfo(), getBase().getInfo(), calculateCost(), vegInfo);
//Return list of toppings, Total Price, vegetarian
}
}
Try this:
String menuString="";
for (Map.Entry<String, Pizza> pizzaItem : namedPizzas.entrySet()) {
menuString += pizzaItem.getKey() + "\n";
menuString += "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
public String printMenu()
{
String s ="";
for (String key: namedPizzas.keySet()){
s+= pizzaItem.getKey() + "\n";
s+= "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
return menuString
}
To address your question directly:
You need a set of keys. With a set of keys you can also get values. HashMap#keySet should work for this. You can loop through a set using a for each loop.
Then as you said, you need to build your string and return. Putting it together gives you:
public String printMenu()
{
String menuString = "";
for(String key : namedPizzas.keySet())
{
menuString += key + "\n" +
"\t" + namedPizzas.get(key).getInfo() + "\n\n";
}
return menuString;
}
I would also like to suggest a design improvement. You should be overriding the Object#toString method for things like this. The toString method will get automatically called when you try to print the object. This allows you to do: System.out.println(myPizzaMenu); instead of System.out.println(myPizzaMenu.printMenu());
The name printMenu is also misleading, so for that reason it's also bad.
Unfortunately, after switching the map to a list, it still didn't work. An hour later I found the bug causing it all! Thanks for everyone's answers, I will keep these methods in mind when I need to use maps again.
EDIT: Here is the new class structure for reference:
public class PizzaMenu
{
static List<Pizza> namedPizzas = new ArrayList<Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
pizza.setName(name.toLowerCase());
namedPizzas.add(pizza);
}
public static String printMenu()
{
String menuString="";
Pizza p;
//Collect all pizzas and add their information to string
for (int i =0; i<namedPizzas.size(); i++)
{
p = namedPizzas.get(i);
menuString+=p.getName().toUpperCase()+"\n"+p.getInfo()+"\n\n";
p.resetCost();
}
return menuString;
}
}

Categories

Resources