简体   繁体   English

我如何在此类中访问公共数组

[英]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. 我想做的是在具有主要方法的测试类中调用变量coinArray 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. 我在测试类中添加了一条print语句,以查看是否向数组添加了任何数据,但是printout为null,因此没有数据。 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. 这是因为coinArray永远不会在您的代码中更改。 You are only changing the coins variable in the object. 您仅更改对象中的coins变量。

Have you tried adding a proxy method on PiggyBank to access the toArray method of Bag ? 您是否尝试过在PiggyBank上添加代理方法以访问Bag的toArray方法?

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

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

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