Ali*_*cia 0 java variables methods static
好的,所以我已经发布了第一部分(我没有获得热狗机销售的正确输出)并获得了大量的帮助,但现在我无法想出从所有不同的展台返回正确的总数.我通过使用'this'关键字让支架增加,但我无法弄清楚如何让静态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;
}
}
Run Code Online (Sandbox Code Playgroud)
和我的测试课
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());
}
Run Code Online (Sandbox Code Playgroud)
}
返回:第1站售出5第2站售出3第3站售出9所有看台售出的热狗总数为9
因此它正确地调用justSold方法并正确递增,但它只是从一个支架中拉出总数.
每次调用justSold()时都会更改totalSold,而不是根据需要递增它.即改变这个:
public void justSold()
{
this.hotDogsSold++;
totalSold=hotDogsSold;
}
Run Code Online (Sandbox Code Playgroud)
对此:
public void justSold()
{
this.hotDogsSold++;
totalSold++;
}
Run Code Online (Sandbox Code Playgroud)