简体   繁体   English

Java在没有调试器的情况下运行时仅打印HashMap的最后一个条目

[英]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. 我希望我的程序打印HashMap中的所有条目,并且如果我在调试器中运行该应用程序,它也会这样做。 But if I run it normaly it prints only the last entry :( Have no idea why it does, Please help me. 但是,如果我正常运行它,它只会打印最后一个条目:(不知道为什么这样做,请帮助我。

MoneyCounter: 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. 我使用GregorainCalendar作为HashMap键。 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. 当您在调试器中运行程序时,您无法在一瞬间按10次下一步,因此时间不同,因此键也不同,因此它返回所有条目。

Be attentive when use time and all will be Ok :) 使用时间专心一点,一切都会好的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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