Having some trouble with the BlackJack Java card total ouptput - java

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())

Related

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 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.

Get product name from Array list object

I'm creating small javaEE Application I have problem with vendorsProdcut name dropdownbox is not showing name only array object like this see the images
Just want to ask how can I get the product name from arraylist to fix my problem?
just wondering is there are away to bring arraylist product name from
productViewModel.getAllProductForVendor
HTML
<div class="ui-block-a">
<h:selectOneMenu id="productname" value="#{productViewModel.prodname}" onchange="javascript: return this.form.submit();">
<f:selectItems value="#{productViewModel.getAllProductForVendor(vendorViewModel.vendorno)}"></f:selectItems>
</h:selectOneMenu>
</div>
Java Beans
public ArrayList<ProductEJBDTO> getAllProductForVendor(int vendorno) {
ArrayList<ProductEJBDTO> Products = new ArrayList() ;
//model.getProducts(vendorno);
try
{
Products = productFacadeBean.getAllProductsForVendor(vendorno);
}
catch(Exception e)
{
System.out.println("can't get products for vendors " + e);
}
return Products;
}
DTO
package case2dtos;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* #author abdallaelnajjar
*/
public class ProductEJBDTO implements Serializable {
public ProductEJBDTO(){}
private int vendorno;
private String prodcd;
private String vensku;
private String prodnam;
private BigDecimal costprice;
private BigDecimal msrp;
private int rop;
private int eoq;
private int qoh;
private int qoo;
private byte[] qrcode;
/**
* #return the prodcd
*/
public String getProdcd() {
return prodcd;
}
/**
* #param prodcd the prodcd to set
*/
public void setProdcd(String prodcd) {
this.prodcd = prodcd;
}
/**
* #return the vensku
*/
public String getVensku() {
return vensku;
}
/**
* #param vensku the vensku to set
*/
public void setVensku(String vensku) {
this.vensku = vensku;
}
/**
* #return the prodnam
*/
public String getProdnam() {
return prodnam;
}
/**
* #param prodnam the prodnam to set
*/
public void setProdnam(String prodnam) {
this.prodnam = prodnam;
}
/**
* #return the costprice
*/
public BigDecimal getCostprice() {
return costprice;
}
/**
* #param costprice the costprice to set
*/
public void setCostprice(BigDecimal costprice) {
this.costprice = costprice;
}
/**
* #return the msrp
*/
public BigDecimal getMsrp() {
return msrp;
}
/**
* #param msrp the msrp to set
*/
public void setMsrp(BigDecimal msrp) {
this.msrp = msrp;
}
/**
* #return the rop
*/
public int getRop() {
return rop;
}
/**
* #param rop the rop to set
*/
public void setRop(int rop) {
this.rop = rop;
}
/**
* #return the eoq
*/
public int getEoq() {
return eoq;
}
/**
* #param eoq the eoq to set
*/
public void setEoq(int eoq) {
this.eoq = eoq;
}
/**
* #return the qoh
*/
public int getQoh() {
return qoh;
}
/**
* #param qoh the qoh to set
*/
public void setQoh(int qoh) {
this.qoh = qoh;
}
/**
* #return the qoo
*/
public int getQoo() {
return qoo;
}
/**
* #param qoo the qoo to set
*/
public void setQoo(int qoo) {
this.qoo = qoo;
}
/**
* #return the qrcode
*/
public byte[] getQrcode() {
return qrcode;
}
/**
* #param qrcode the qrcode to set
*/
public void setQrcode(byte[] qrcode) {
this.qrcode = qrcode;
}
/**
* #return the vendorno
*/
public int getVendorno() {
return vendorno;
}
/**
* #param vendorno the vendorno to set
*/
public void setVendorno(int vendorno) {
this.vendorno = vendorno;
}
}
Override the toString() method in the ProductEJBDTO to return the name.
public class ProductEJBDTO implements Serializable {
...
...
#Override
public String toString() {
return this.prodnam; // The product name you want to display.
}
}
Use the itemLabel attribute (docs):
<f:selectItems value="..." var="x" itemLabel="#{x.prodnam}"></f:selectItems>
(I assume the prodnam property is the desired display name; any EL expression will do though)

Jtable not showing data after adding all in a baund observablelist

I am having some difficult on a jtable bound on a observablelist of objects called EntradaMercadoriaList. After adding all objects in this list, jtable shows only empty rows equivalent of the list size
here is my code:
List <EntradaMercadoria> merc = new ArrayList<EntradaMercadoria>();
for (int i = 0; i < entradasList.size(); i++) {
int nf = entradasList.get(i).getDocOrigem();
int tipo = entradasList.get(i).getTipoDocOrigem().getIdesPecasTipoOrigem();
String fornecedor = "não-aplicado";
if (tipo == 2) {
NfTerc nfTerc;
nfTerc = entityManager.find(NfTerc.class, entradasList.get(i).getDocOrigem());
fornecedor = nfTerc.getFornecedoresNumForn().getNumForn() + " - " + nfTerc.getFornecedoresNumForn().getCodPessoa().getNomePessoa();
}
boolean novo = true;
for (int j = 0; j < merc.size(); j++) {
if (nf == merc.get(j).getnDoc() && fornecedor.equals(merc.get(j).getFornecedor())) {
merc.get(j).setQuantidade(merc.get(j).getQuantidade() + 1.00);
novo = false;
}
}
if (novo) {
EntradaMercadoria em = new EntradaMercadoria();
em.setDataEmissao(entradasList.get(i).getDataOrigem());
em.setFornecedor(fornecedor);
em.setQuantidade(1.00);
em.setTipoDoc(tipo);
em.setnDoc(nf);
merc.add(em);
}
}
entradaMercadoriaList.clear();
entradaMercadoriaList.addAll(merc);
Here is my EntadaMercadoria object:
import java.util.Date;
/**
*
* #author Bernardo
*/
class EntradaMercadoria {
private int nDoc;
private int tipoDoc;
private String fornecedor;
private double quantidade;
private Date dataEmissao;
public EntradaMercadoria() {
}
/**
* #return the nDoc
*/
public int getnDoc() {
return nDoc;
}
/**
* #param nDoc the nDoc to set
*/
public void setnDoc(int nDoc) {
this.nDoc = nDoc;
}
/**
* #return the tipoDoc
*/
public int getTipoDoc() {
return tipoDoc;
}
/**
* #param tipoDoc the tipoDoc to set
*/
public void setTipoDoc(int tipoDoc) {
this.tipoDoc = tipoDoc;
}
/**
* #return the fornecedor
*/
public String getFornecedor() {
return fornecedor;
}
/**
* #param fornecedor the fornecedor to set
*/
public void setFornecedor(String fornecedor) {
this.fornecedor = fornecedor;
}
/**
* #return the quantidade
*/
public double getQuantidade() {
return quantidade;
}
/**
* #param quantidade the quantidade to set
*/
public void setQuantidade(double quantidade) {
this.quantidade = quantidade;
}
/**
* #return the dataEmissao
*/
public Date getDataEmissao() {
return dataEmissao;
}
/**
* #param dataEmissao the dataEmissao to set
*/
public void setDataEmissao(Date dataEmissao) {
this.dataEmissao = dataEmissao;
}
}
What is wrong? is There a way to refresh table to show data in lines?
Thanks.

Categories

Resources