我目前正在進行類分配,並且無法弄清楚爲什麼我得到的是輸出。編程問題是:Java程序不返回任何值
您運行幾個熱狗站。定義一個名爲
HotDogStand
的類,該類具有熱狗站標識號的實例變量以及當天銷售的熱狗數量的實例變量 。 創建一個構造函數,允許該類的用戶初始化兩個變量 。還要創建一個名爲justSold
的方法,該方法可以通過 增加一個展位銷售的熱狗數量。這個想法是,這個 方法將在每次售賣熱狗時被調用,因此可以跟蹤總共 。添加另一種方法,返回銷售熱狗的數量 。添加一個靜態變量,該變量跟蹤 所有看臺出售的熱狗總數以及一個返回此變量值的靜態方法。
所以我的代碼是:
public class HotDogStand {
// instance variable declaration
private int IDNumber;
private int hotDogsSold = 0;
private static int totalSold = 0;
public HotDogStand(int ID, int sold) {
IDNumber = ID;
hotDogsSold = sold;
}
public int getID() {
return IDNumber;
}
public void setID(int ID) {
IDNumber = ID;
}
public void justSold() {
if (hotDogsSold > 0) {
hotDogsSold++;
}
}
public int sold() {
return hotDogsSold;
}
public static int getTotal() {
return totalSold;
}
}
而且我的測試類是:
public class HotDogTest {
public static void main(String[] args) {
HotDogStand stand1 = new HotDogStand(1, 11);
HotDogStand stand2 = new HotDogStand(2, 17);
HotDogStand stand3 = new HotDogStand(3, 6);
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();
stand1.getTotal();
stand2.getTotal();
stand3.getTotal();
int grandTotal = stand1.getTotal() + stand2.getTotal() + stand3.getTotal();
System.out.println("Stand " + stand1.getID() + " sold a total of " + stand1.getTotal() + " hotdogs.");
System.out.println("Stand " + stand2.getID() + " sold a total of " + stand2.getTotal() + " hotdogs.");
System.out.println("Stand " + stand3.getID() + " sold a total of " + stand3.getTotal() + " hotdogs.");
System.out.println("The total amount of hotdogs sold by all the stands was " + grandTotal);
}
}
我的輸出是:
站1共0熱狗出售。
2號臺共售出0個熱狗。
展臺3總共銷售了0條熱狗。
所有攤位出售的熱狗總量爲0
您正在增加'hotDogsSold',但打印返回'totalSold'的getTotal()。 – barunsthakur
你用什麼來達到目的:'if(hotDogsSold> 0){hotDogsSold ++; }'? – Tom
有點不清楚你想要什麼程序。在函數名稱或描述中使用獲取或設置/更新/增加使用更清晰的名稱。 –