如何从静态方法中获取总数

时间:2015-06-26 22:14:58

标签: java variables methods static

好的,所以我已经发布了第一部分(我没有得到热狗机销售的正确输出)并获得了大量的帮助,但现在我无法找到返回正确的来自所有不同看台的总数。我通过使用'这个'来增加看台。关键字,但我无法弄清楚如何让静态getTotal正确地增加所有看台。

public class HotDogStand {

    //instance variable declaration
    private int IDNumber;
    private int hotDogsSold=0;
    private static int totalSold=0;
    //constructor
    public HotDogStand(int ID, int sold)
    {
        this.IDNumber=ID;
        this.hotDogsSold=sold;
    }
    //sets ID for all the stands
    public void setID(int ID)
    {
        this.IDNumber=ID;
    }
    public int getID()
    {
        return IDNumber;
    }
    //invoked each time a stand makes a sale
    public void justSold()
    {
            this.hotDogsSold++;
            totalSold=hotDogsSold;
    }
    //gets the totals for the different stands
    public int getSold()
    {
        return this.hotDogsSold;
    }

    // returns total sales of all stands
    public static int getTotal()
    {
        return totalSold;
    }

}

和我的测试类

public class HotDogTest {
public static void main(String[]args){
    HotDogStand stand1=new HotDogStand(1, 1);
    HotDogStand stand2=new HotDogStand(2, 2);
    HotDogStand stand3=new HotDogStand(3, 7);

    stand1.getID();
    stand2.getID();
    stand3.getID();
    stand1.setID(1);
    stand2.setID(2);
    stand3.setID(3);
    stand1.justSold();
    stand2.justSold();
    stand3.justSold();
    stand1.justSold();
    stand1.justSold();
    stand1.justSold();
    stand3.justSold();

    System.out.println("Stand " + stand1.getID() + " sold " + stand1.getSold());
    System.out.println("Stand " + stand2.getID() + " sold " + stand2.getSold());
    System.out.println("Stand " + stand3.getID() + " sold " + stand3.getSold()); 

    System.out.println("The total amount of hotdogs sold by all the stands was "+HotDogStand.getTotal());

}

}

返回: 1号摊位卖5 2号摊位3 3号展位售出9 所有看台销售的热狗总数为9

因此它正确调用justSold方法并正确递增,但它只是从一个支架中拉出总数。

2 个答案:

答案 0 :(得分:5)

每次调用justSold()时都会更改totalSold,而不是根据需要增加它。即改变这一点:

public void justSold()
{
        this.hotDogsSold++;
        totalSold=hotDogsSold;
}

到此:

public void justSold()
{
        this.hotDogsSold++;
        totalSold++;
}

答案 1 :(得分:3)

您正在使用的替代方法是将创建的展位维护在列表中并按需计算总计。这取决于您的使用案例。

以下是:

public class HotDogStand {

    // create static list of all stands created
    private List<HotDogStand> stands = new ArrayList<HotDogStand>();

    //  in the constructor, make sure the stand is added to the list
    public HotDogStand(...){
        HotDogStand.stands.add(this);
        // ...
    }

    // ...

    // calculate total sales of all stands using the list
    public static int getTotal()
    {
        int total = 0;
        for (HotDogStand stand : HotDogStand.stands){
            total += stand.getSold();
        }
        return total;
    }

}