简体   繁体   中英

How can I access the public array in this class

package bagimplementation.ch1;
import bagimplementation.Bag;
import bagimplementation.BagInterface;
import java.util.Arrays;
/**
 * A class that implements a piggy bank by using a bag.
 * @author Jeff Nicholas
 */
public class PiggyBank {
    private BagInterface<Coin> coins;
    public static String[] coinsArray;
    public PiggyBank(){
        coins = new Bag<Coin>();
    }

    public boolean add(Coin aCoin){
        return coins.add(aCoin);
    }

    public Coin remove(){
        return coins.remove();
    }

    public boolean isEmpty(){
        return coins.isEmpty();
    }

}

What I want to do is call the variable coinsArray within the test class which has the main method. I added a print statement to the test class to see if I have any data added to the array but the printout is null, so it has no data. The test class follows

public class PiggyBankExample {

    public static void main(String[] args){
        PiggyBank myBank = new PiggyBank();

        addCoin(new Coin(1, 2010), myBank);
        addCoin(new Coin(5, 2011), myBank);
        addCoin(new Coin(10, 2000), myBank);
        addCoin(new Coin(25, 2012), myBank);

        System.out.println((PiggyBank.coinsArray));
        System.out.println("Removing all the coins:");
        int amountRemoved = 0;

        while(!myBank.isEmpty()){
            Coin removedCoin = myBank.remove();

            System.out.println("Removed a " + removedCoin.getCoinName() + 
                               ".");
            amountRemoved += removedCoin.getCoin();
        }

        System.out.println("All done. Removed " + amountRemoved + " cents.");
    }

    private static void addCoin(Coin aCoin, PiggyBank aBank){
        if(aBank.add(aCoin)){
            System.out.println("Added a " + aCoin.getCoinName() + ".");
        }else{
            System.out.println("Tried to add a " + aCoin.getCoinName() +
                               ", but couldn't");
        }
    }


}

That's because coinsArray is never changed in your code. You are only changing the coins variable in the object.

Have you tried adding a proxy method on PiggyBank to access the toArray method of Bag ?

public Object[] toArray() {
    return coins.toArray();
}

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