World of Zuul - adding items using an ArrayList - java

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

Related

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 invoke ParkingTicket(parker, parkee)?

Here is my problem I can't seem to figure out how to invoke a ParkingTicket object if (carMinutesPaid>meterMinutesPaid)? can any one help here are the details below to the question.
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
System.out.println("null");
}
return new ParkingTicket(parker, parkee);
}
Here is the question for my project.
Remember, this method must be able to be used without a ParkingTicket object in existence.
Using a Car parameter and a ParkingMeter parameter, decide whether a ParkingTicket object should be created.
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and return the result.
Return null if a ticket was not merited.
Here is my car class:
/**
* This is a Car class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class Car
{
private static final int MINIMUM_PLATE_LENGTH=2;
private static final int MAXIMUM_PLATE_LENGTH=7;
public static final char MANUAL_TRANSMISSION='m';
public static final char AUTOMATIC_TRANSMISSION='a';
private static int defaultMinutesParked = 0;
private static double defaultOdometerInKm = 50000.5;
private String licensePlate;
private char transmissionType;
private double odometerInKm;
private int minutesParked;
/**
* #param newProposedLicensePlate the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public Car(String newProposedLicensePlate)
{
setLicensePlate(newProposedLicensePlate);
transmissionType = AUTOMATIC_TRANSMISSION;
odometerInKm = defaultOdometerInKm;
minutesParked = defaultMinutesParked;
}
/**
* #return the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public String getLicensePlate()
{
return licensePlate;
}
/**
* #return the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
*/
public char getTransmissionType()
{
return transmissionType;
}
/**
* #return the odometer in kilometers
*/
public double getOdometerInKm()
{
return odometerInKm;
}
/**
* Recieve the license plate
* Mutator.licensePlate.
* #param proposedLicense String Conforming to ICBC *length* guidlines:
* http://www.icbc.com/vehicle-registration/license-plates/Pages/Personalized-licence-plates.aspx
* May also be null. The null represents a car without a plate
* If validation fails, null will be set.
*/
public void setLicensePlate(String proposedLicense)
{
if(proposedLicense==null){
licensePlate = proposedLicense;
}
else if(proposedLicense.length()>=MINIMUM_PLATE_LENGTH && proposedLicense.length()<=MAXIMUM_PLATE_LENGTH){
licensePlate = proposedLicense;
}
else{
licensePlate = null;
}
}
/**
* #param mOrA recieve the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
* if invalid type of transmission is entered then will return "Installation failure: 'mOrA' is not a vaild transmission type"
*/
public void setTransmissionType(char mOrA)
{
if(mOrA==MANUAL_TRANSMISSION){
transmissionType = mOrA;
}
else if(mOrA==AUTOMATIC_TRANSMISSION){
transmissionType = mOrA;
}
else if (mOrA==mOrA){
System.out.println("Installation failure:" + " " + ("'")+(mOrA)+("'") + " " + "is not a valid transmission type.");
}
else{
transmissionType = mOrA;
}
}
/**
* #return the value of the odometer in with the String kilometers
*/
public String readOdometer()
{
return odometerInKm + " " + "kilometers";
}
/**
* #return the false if the minutesParked equals zero; otherwise true
*/
public boolean isParked()
{
if(minutesParked==defaultMinutesParked){
return false;
}
else{
return true;
}
}
/**
* #param duration replaces any existing value in minutesParked with the value from duration
*/
public void park(int duration)
{
if(duration>=defaultMinutesParked){
minutesParked = duration;
}
}
/**
* #param aOdometerInKm recieve the odometer in kilometers
*/
public void setOdometerInKm(double aOdometerInKm)
{
odometerInKm = aOdometerInKm;
}
/**
* #param aMinutesParked recieve the minutes parked in the stall but can not be a negative number
* if invalid number of minutes is entered then the number of minutes will not change.
*/
public void setMinutesParked(int aMinutesParked)
{
if(aMinutesParked>=defaultMinutesParked){
minutesParked = aMinutesParked;
}
else{
return;
}
}
/**
* #return the minutes parked
*/
public int getMinutesParked()
{
return minutesParked;
}
}
here is my ParkingMeter class:
/**
* This is a ParkingMeter class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class ParkingMeter
{
private int minutesPaid;
private String methodPaid;
/**
* #param newMinutesPaid the minutes paid for parking meter
*/
public ParkingMeter()
{
}
/**
* #return the minutes paid
*/
public int getMinutesPaid()
{
return minutesPaid;
}
/**
* #return the method paid
*/
public String getMethodPaid()
{
return methodPaid;
}
/**
* #param paidBy the payment method customer will paid by
*/
public void setMethodPaid(String paidBy) /* BONUS for creating method paid */
{
if(methodPaid=="Visa"){
methodPaid = paidBy;
}
else if(methodPaid=="Master Card"){
methodPaid = paidBy;
}
else if(methodPaid=="American Express"){
methodPaid = paidBy;
}
else if(methodPaid=="Cash"){
methodPaid = paidBy;
}
else if(methodPaid=="Debit"){
methodPaid = paidBy;
}
else{
methodPaid = paidBy;
}
}
/**
* #param quantity the added minutes paid must not have a negative number
*/
public void addMinutesPaid(int quantity)
{
if(quantity>=0){
minutesPaid+=quantity;
}
}
}
and here is my ParkingTicket class:
/**
* This is a ParkingTicket class for Impark.
*
* #author Tre
* #version 1.0
*/
public class ParkingTicket
{
private final String referenceNumber;
private static String carLicensePlate;
private static int carMinutesParked;
private static int meterMinutesPaid;
private static int count = 1000;
private static String PREFIX = "V";
/**
* #param recorededLicense the value of the tick number
*/
private ParkingTicket(String recordedLicense, int newCarMinutesParked, int newMeterPaidMinutes)
{
referenceNumber = (PREFIX+count++);
carMinutesParked = newCarMinutesParked;
meterMinutesPaid = newMeterPaidMinutes;
}
/**
* #param
*/
private ParkingTicket(Car parker, ParkingMeter parkee)
{
this(parker.getLicensePlate(), parker.getMinutesParked(), parkee.getMinutesPaid());
}
/**
* #return referenceNumber the reference number
*/
public String getReferenceNumber()
{
return referenceNumber;
}
/**
* #return carLicensePlate the car's license plate
*/
public String getCarLicensePlate()
{
return carLicensePlate;
}
/**
* #return carMinutesParked the minutes car was parked
*/
public int getCarMinutesParked()
{
return carMinutesParked;
}
/**
* #return meterMinutesPaid the minutes paid on meter
*/
public int getMeterMinutesPaid()
{
return meterMinutesPaid;
}
/**
* #return count the with initial value of 1000
*/
public int getCount()
{
return count;
}
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
return null;
}
return new ParkingTicket(parker, parkee);
}
}
This requirement:
Using a Car parameter and a ParkingMeter parameter, decide whether a
ParkingTicket object should be created.
suggests that you provide two parameters to the checkParking method, one is of the type Car and one of the ParkingMeter. So it should be like so:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
This code :
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
won't even compile
line 1: you're trying to assign int to object - that's called type mismatch.
line 2: variable parkee is not declared anywhere (except for the headline of the question).
You see, only the Car object holds the information about the parking duration, and you need the object for creating parking ticket. Same for the ParkingMeter
It should be vice versa - you get the values from the objects:
int carMinutesParked = car.getMinutesParked();
int meterMinutesPaid = meter.getMinutesPaid();
and proceed from here with if( or even use it in if without declaring temporary variables).
This one:
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and
return the result.
you did OK.
Now this requirement:
Return null if a ticket was not merited.
suggest the method will return null, not string that equals to "null" .
So, based on these requirements it should rather be:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
{
//sanity check (bonus)
if ((car == null) || (meter == null))
return null;
if(car.getMinutesParked() > meter.getMinutesPaid()){
return new ParkingTicket(car, meter);
}
return null;
}
Note however, I don't know if you need any additional logic in this code and don't suggest this should be your final version, just explaining the general approach.

implementing a linked list with StockList

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!

How do you call methods into an object array?

I have two classes. A class called Cat, that holds the cat names, birth year and weight in kilos. I have a class called Cattery that is an array. I want to input cats from the Cat class into the array. Each cat will have its own name, birth year and weight in Kilos. How do I do this? Thank you.
public class Cat {
private String name;
private int birthYear;
private double weightInKilos;
/**
* default constructor
*/
public Cat() {
}
/**
* #param name
* #param birthYear
* #param weightInKilos
*/
public Cat(String name, int birthYear, double weightInKilos){
this.name = name;
this.birthYear = birthYear;
this.weightInKilos = weightInKilo
}
/**
* #return the name.
*/
public String getName() {
return name;
}
/**
* #return the birthYear.
*/
public int getBirthYear() {
return birthYear;
}
/**
* #return the weightInKilos.
*/
public double getWeightInKilos() {
return weightInKilos;
}
/**
* #param the name variable.
*/
public void setName(String newName) {
name = newName;
}
/**
* #param the birthYear variable.
*/
public void setBirthYear(int newBirthYear) {
birthYear = newBirthYear;
}
/**
* #param the weightInKilos variable.
*/
public void setWeightInKilos(double newWeightInKilos) {
weightInKilos = newWeightInKilos;
}
}
The array class.
import java.util.ArrayList;
public class Cattery {
private ArrayList<Cat> cats;
private String businessName;
/**
* #param Cattery for the Cattery field.
*/
public Cattery() {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
/**
* Add a cat to the cattery.
* #param catName the cat to be added.
*/
public void addCat(Cat name)
{
Cat.add(getName());
}
/**
* #return the number of cats.
*/
public int getNumberOfCats()
{
return cats.size();
}
}
just edit the "addCat" method to pass object from argument to your ArrayList.
public void addCat(Cat name)
{
cats.add(name);
}
It seems that what you are trying to do is add cats to the cats list you declared in your Cattery. Another answer already notes the correction needed - your addCat method must be modified then to actually put the cats in the list. Note that you're not adding the cat name, but an actual Cat object. It also seems like you want the Cattery to have a business name. You can pass that in to the constructor.
public Cattery(String businessName) {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
...
public void addCat(Cat cat)
{
cats.add(cat);
}
Here's an example of how you may create your cattery and subsequently add cats. You must love cats.
class CatApp{
public static void main(String[] args) {
Cattery cattery = new Cattery("The Delicious Cats Business");
cattery.addCat(New Cat("Milo", 3, 388.87));
cattery.addCat(New Cat("Otis", 2, 1.4));
System.out.println("Total number of cats ready for consumption = "
+ cattery.getNumberOfCats());
}
}

Having some trouble with the BlackJack Java card total ouptput

So I am creating this BlackJack Java game that uses many different classes to learn how to program using OO. I'm really stuck on this one particular part however, getting the code to display the correct card in the hand. It just displays a weird string such as com.game.blackjack.Hand#18e2b22, or has a different display of characters. Wondering how this can be converted into an actual card value and rank?
public class Suit {
public static final int SPADE = 0, HEART = 1, DIAMOND = 2, CLUB = 3;
/**
* Maps the names for the suits as a string.
*/
private Map<Integer, String> suitMap = new HashMap<Integer, String>();
/**
* ID for the suit
*/
private int suitId = 0;
/**
* sets the id for the suit to get.
*/
public Suit(int suitId) {
suitMap.put(SPADE, "Spades");
suitMap.put(HEART, "Hearts");
suitMap.put(DIAMOND, "Diamonds");
suitMap.put(CLUB, "Clubs");
this.suitId = suitId;
}
public String toString() {
return suitMap.get(suitId);
}
/**
* #param suitId
* #return suitMap
*/
public String getSuitNameById(int suitId) {
return suitMap.get(suitId);
}
/**
* #return id of suit
*/
public String getSuitName() {
return suitMap.get(suitId);
}
/**
* #return the suitId
*/
public int getSuitId() {
return suitId;
}
/**
* #param suitId the suitId to set
*/
public void setSuitId(int suitId) {
this.suitId = suitId;
}
/**
* #return the suitMap
*/
public Map<Integer, String> getSuitMap() {
return suitMap;
}
/**
* #param suitMap the suitMap to set
*/
public void setSuitMap(Map<Integer, String> suitMap) {
this.suitMap = suitMap;
}
}
public class Card {
private boolean stateOfCard = false;
/**
* Gives the constant values to ace jack queen and king for being special
* types of cards.
*/
public final static int ACE = 1, JACK = 11, QUEEN = 12, KING = 13;
/**
* Maps names to the ace jack queen and king cards.
*/
private Map<Integer, String> nameMap = new HashMap<Integer, String>();
/**
* Rank or type of card (2-9, J,Q,K, A)
*/
private String cardRank = null;
/**
* Card suit
*/
private Suit suit = null;
/**
* Numeric value of the card
*/
private int cardValue = 0;
/**
* Gives you the suit, cardRank, and the cardValue
*/
public Card(Suit suit, String cardRank, int cardValue) {
nameMap.put(ACE, "Ace");
nameMap.put(JACK, "Jack");
nameMap.put(QUEEN, "Queen");
nameMap.put(KING, "King");
if (cardValue >= 11 || cardValue == 1) cardRank = nameMap.get(cardValue);
this.suit = suit;
this.cardRank = cardRank;
this.cardValue = cardValue;
}
/**
* Displays to user the rank and suit of the card.
*/
public String toString() {
return cardRank + " of " + suit.getSuitName();
}
/**
* #return the cardRank
*/
public String getCardRank() {
return cardRank;
}
/**
* #param cardRank the cardRank to set
*/
public void setCardRank(String cardRank) {
this.cardRank = cardRank;
}
/**
* #return the suit
*/
public Suit getSuit() {
return suit;
}
/**
* #param suit the suit to set
*/
public void setSuit(Suit suit) {
this.suit = suit;
}
/**
* #return the cardValue
*/
public int getCardValue() {
return cardValue;
}
/**
* #param cardValue the cardValue to set
*/
public void setCardValue(int cardValue) {
this.cardValue = cardValue;
}
/**
* #return the nameMap
*/
public Map<Integer, String> getNameMap() {
return nameMap;
}
/**
* #param nameMap the nameMap to set
*/
public void setNameMap(Map<Integer, String> nameMap) {
this.nameMap = nameMap;
}
/**
* #return the stateOfCard
*/
public boolean isStateOfCard() {
return stateOfCard;
}
/**
* #param stateOfCard the stateOfCard to set
*/
public void setStateOfCard(boolean stateOfCard) {
this.stateOfCard = stateOfCard;
}
}
public class Deck {
/**
* Deck of cards created
*/
private ArrayList<Card> deck = new ArrayList<Card>();
/**
* Keeps track of the cards that are dealt and no longer available
*/
private List<Card> cardUsed = new ArrayList<Card>();
/**
* The array of cards in a set. Can be shuffled and drawn from. Deck of any #.
* #param cards
*/
public Deck(int numCards) {
this.createDeck(numCards, 4);
}
/**
* creates a deck that has cards in it with 4 suits of each 13 cards.
* #param numCards
* #param numSuits
*/
private void createDeck(int numCards, int numSuits) {
deck = new ArrayList<Card>();
cardUsed = new ArrayList<Card>();
if ((numCards % numSuits) > 0) return;
for (int i=0; i < numSuits; i++) {
for(int j=1; j <= (numCards / numSuits); j++) {
deck.add(new Card(new Suit(i), j + "", j));
}
}
}
/**
* Deals a card to the hand. Sends dealt card to the cardUsed list so that
* a used card will not be drawn again unless deck is shuffled.
* #return dealtCard
*/
public Card dealCard( ) {
Card dealtCard = null;
if (deck.size() == 0){
deck.addAll(cardUsed);
this.shuffle();
cardUsed = new ArrayList<Card>();
}
dealtCard = deck.get(0);
deck.remove(0);
cardUsed.add(dealtCard);
return dealtCard;
}
/**
* Shuffles the cards after every round.
*/
public void shuffle() {
Collections.shuffle(deck);
}
/**
* #return the deck
*/
public ArrayList<Card> getDeck() {
return deck;
}
/**
* #param deck the deck to set
*/
public void setDeck(ArrayList<Card> deck) {
this.deck = deck;
}
/**
* Returns the number of used cards
* #return
*/
public int getNumUsedCards() {
return cardUsed.size();
}
/**
* #return the cardUsed
*/
public List<Card> getCardUsed() {
return cardUsed;
}
/**
* #param cardUsed the cardUsed to set
*/
public void setCardUsed(List<Card> cardUsed) {
this.cardUsed = cardUsed;
}
}
public class Hand {
private ArrayList<Card> hand = new ArrayList<Card>();
int total = 0;
/**
* A list of cards that can be defined as hand. Player has a list of these
* cards in a hand.
*/
public Hand(){
}
public boolean isAce() {
return false;
}
public boolean discardHand(){
if (hand.isEmpty()) {
hand = new ArrayList<Card>();
}
return false;
}
/**
* Adds the card to the hand in a list of cards.
* #param c
*/
public void addCard(Card c) {
this.hand.add(c);
}
/**
* Gets the place value of the card in the hand.
* #param index
* #return index of card in hand
*/
public Card getPosition(int index){
return hand.get(index);
}
/**
* Gets how many cards are in the player's hand.
* #return hand size
*/
public int handCardCount(){
return hand.size();
}
/**
* #return the total
*/
public int getTotal() {
return total;
}
/**
* #param total the total to set
*/
public void setTotal(int total) {
this.total = total;
}
/**
* #return the hand
*/
public ArrayList<Card> getHand() {
return hand;
}
/**
* #param hand the hand to set
*/
public void setHand(ArrayList<Card> hand) {
this.hand = hand;
}
}
public class Player extends Person {
private Hand myCards = new Hand();
private int playerCashAmount = 100;
public Player() {
}
public Player(String name) {
this.name = name;
}
/**
* Gets the name of the user from the parent class
*/
public String getName() {
return super.getName();
}
/**
* #return the playerCashAmount
*/
public int getPlayerCashAmount() {
return playerCashAmount;
}
/**
* #param playerCashAmount the playerCashAmount to set
*/
public void setPlayerCashAmount(int playerCashAmount) {
this.playerCashAmount = playerCashAmount;
}
/**
* #return the myCards
*/
public Hand getMyCards() {
return myCards;
}
/**
* #param myCards the myCards to set
*/
public void setMyCards(Hand myCards) {
this.myCards = myCards;
}
}
public class Dealer extends Person {
private String dealCards = null;
private String playCards = null;
private String shuffleDeck = null;
private Hand computerCards = new Hand();
/**
*
*/
public Dealer() {
}
/**
* #return the dealCards
*/
public String getDealCards() {
return dealCards;
}
/**
* #param dealCards the dealCards to set
*/
public void setDealCards(String dealCards) {
this.dealCards = dealCards;
}
/**
* #return the playCards
*/
public String getPlayCards() {
return playCards;
}
/**
* #param playCards the playCards to set
*/
public void setPlayCards(String playCards) {
this.playCards = playCards;
}
/**
* #return the shuffleDeck
*/
public String getShuffleDeck() {
return shuffleDeck;
}
/**
* #param shuffleDeck the shuffleDeck to set
*/
public void setShuffleDeck(String shuffleDeck) {
this.shuffleDeck = shuffleDeck;
}
/**
* #return the computerCards
*/
public Hand getComputerCards() {
return computerCards;
}
/**
* #param computerCards the computerCards to set
*/
public void setComputerCards(Hand computerCards) {
this.computerCards = computerCards;
}
}
public class Person {
protected String name = null;
Hand h = new Hand();
/**
*
*/
public Person() {
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the h
*/
public Hand getH() {
return h;
}
/**
* #param h the h to set
*/
public void setH(Hand h) {
this.h = h;
}
}
public class GameEngine {
static Scanner in = new Scanner(System.in);
private Dealer dealer = null;
List<Player> players = new ArrayList<Player>();
Hand h = new Hand();
Person p = new Player();
Player pl = new Player();
int bet = 0;
Deck d = null;
int num = 0;
public GameEngine() {
}
/**
* Plays the game by creating a new instance of the gameplay class.
* #param args
*/
public static void main(String[] args) {
GameEngine ge = new GameEngine();
ge.gamePlay();
}
/**
* Game of BlackJack, runs all the methods that it will call to.
*/
public void gamePlay() {
// States the title of the game.
//this.welcomeToGame();
// Shuffles the deck and creates the number of cards for it.
this.deckStart();
// Prompts user for number of players.
//this.howManyPlayers(num);
// Displays welcome message and asks for user's name.
//this.greetUser();
// Deal initial cards
this.beginCardDeal();
// Place bet on the current round.
//this.betAmount(pl, bet);
// Evaluate, get player choice (stay or hit or bust)
//this.evaluatePlayer();
// Evaluate if bust.
//this.isBust();
// Deal more cards to each user.
//this.takeHitOrStay();
// All players bust / stay.
// Evaluate winner.
}
/**
* Initializes the deck and shuffles it.
*/
public void deckStart () {
d = new Deck(52);
d.shuffle();
}
/**
* Displays welcome message to the player.
*/
public void welcomeToGame(){
System.out.println("This is BlackJack (Double Exposure)\n\n");
}
/**
* Asks for name input and then welcomes them with name.
*/
public void greetUser() {
System.out.print("Enter your name: ");
p.setName(in.next());
System.out.println("Welcome, " + p.getName() + ".");
}
/**
* Prompts user to input how many opponents they would like to face in the game of BlackJack.
* #param num
*/
public void howManyPlayers(int num) {
players = new ArrayList<Player>();
System.out.print("How many other players would you like for this game? Enter here: ");
num = in.nextInt();
for (int i=0; i < num; i++) {
players.add(new Player("Player " + i));
System.out.println(players);
}
}
/**
* Asks the player how much money they will bet on the hand.
* #param pl
* #param bet
*/
public void betAmount(Player pl, int bet) {
while (bet == 0 || bet > pl.getPlayerCashAmount()) {
System.out.print("You have $" + pl.getPlayerCashAmount() + " as of now. Please enter a bet amount: ");
bet = in.nextInt();
System.out.println("You are going to bet $" + bet + ".");
if (bet < 0 || bet > pl.getPlayerCashAmount())
System.out.println("\nYour answer must be between $0 and $" + pl.getPlayerCashAmount());
else if (bet == pl.getPlayerCashAmount())
System.out.println("All in!");
}
}
/**
* Deals the cards to each of the players.
*/
public void beginCardDeal () {
for (int x = 0; x < 2; x++) {
System.out.print("\nDealer is dealing a card. . . \n");
d.dealCard();
System.out.println("\nYour hand: " + pl.getMyCards());
//System.out.println("New hand value test::: " + pl.getMyCards().addCard(d.dealCard()));
}
}
/**
* Checks to see if the player's hand value is over 21. If yes then player
* loses that round.
*/
public void isBust(){
if (h.getTotal() > 21) {
System.out.println("Sorry, you have gone over 21 and busted.");
int money = pl.getPlayerCashAmount() - bet;
System.out.println("You lost $"+bet+", and now you have "+money);
}
}
/**
* Counts the total value of cards each player holds in their hand.
*/
public void evaluatePlayer(){
System.out.println("Your hand value is: ");
System.out.println(pl.getMyCards().getTotal());
}
public String takeHitOrStay(){
while (pl.getMyCards().getTotal() < 21){
System.out.println("Would you like to hit[h] or stay[s]? ");
String choice = in.next();
if (choice.equalsIgnoreCase("h")){
pl.getMyCards();
//System.out.println(pl.getMyCards());
if (choice.equalsIgnoreCase("s")){
System.out.println("Null");
//finish this.
}
}
return choice;
}
return null;
}
/**
* #return the deck
*/
public Deck getDeck() {
return d;
}
/**
* #param deck the deck to set
*/
public void setDeck(Deck deck) {
this.d = deck;
}
/**
* #return the player
*/
public Player getPlayer() {
return pl;
}
/**
* #param player the player to set
*/
public void setPlayer(Player player) {
this.pl = player;
}
/**
* #return the dealer
*/
public Dealer getDealer() {
return dealer;
}
/**
* #param dealer the dealer to set
*/
public void setDealer(Dealer dealer) {
this.dealer = dealer;
}
}
The new problem I am having is that the result I am getting is now null of Spades or 0 of Spades as an output. I added a toString() function into the Hand class.
public String toString(){
return c.getCardValue() + " of " + s.getSuitName();
}
So this has been added to Hand and cleared my first problem of only getting the Hash code for each output. Any ideas on Why I am getting the null of Spades as an output?
You've overridden toString on many classes, but not (yet) on the Hand class. Override toString on Hand to provide your own custom string conversion, or else you'll get the Object implementation of toString, which is to use the class name, an # sign, and the address of the object.
To quote the Javadocs:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

Categories

Resources