简体   繁体   中英

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

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

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