該程序應該花費小時從用戶手機充電,並花費用戶想要爲手機充電的時間(索引0-23),並返回取決於成本的時間根據什麼rateTable說。我遇到的問題是使用getChargeStartTime方法,該方法需要用戶想要爲其手機充電的小時數,並找到開始以最低成本進行充電的最佳時間。我已經能夠讓每種方法都能單獨工作,但它證明是讓他們一致工作的挑戰。需要幫助使方法一起工作
繼承人該程序應該做的一個例子(將使用下面的rateTable的值): 用戶輸入,他們希望從索引4開始爲他們的手機充電3小時。然後getCharging成本索引4並累加接下來的3個值,然後返回88. getChargeStartTime方法將花費小時數並循環遍歷數組,以查找最便宜的充電時間。因此,在這個例子中它最終將找到指數21-23返回40
private int[] rateTable =
{5,10,26,35,23,30,35,40,45,66,58,50,75,
65,30,55,44,45,32,25,31,15,10,15};
private int getChargingCost(int startHour, int chargeTime){
int usercost = 0;
String start = JOptionPane.showInputDialog(
"At what hour do you want to start charging your phone? (0-23)");
startHour = Integer.parseInt(start);
String time = JOptionPane.showInputDialog(
"How many hours do you want to charge your phone?");
chargeTime = Integer.parseInt(time);
for (int hour = 0; hour < chargeTime; hour++){
usercost += rateTable[(startHour + hour) % 24];
}
return usercost;
}
public int getChargeStartTime(int chargeTime) {
int bestStartHour = 0;
int minCost = getChargingCost(0, chargeTime);
for(int hour = 1 ; hour <24 ; hour++){
int cost = getChargingCost(hour, chargeTime);
if(cost < minCost){
bestStartHour = hour;
minCost = cost;
}
return bestStartHour;
}
return chargeTime;
}
public static void main(String[] args){
BatteryCharger obj = new BatteryCharger();
obj.getChargingCost(startHour, chargeTime);
JOptionPane.showMessageDialog(null,
"Charging your phone for " + chargeTime +
" hours will cost $" + usercost + ", but if you start at hour " + bestStartHour + " it will only cost you " + cost);
}
}
'obj.getChargingCost(startHour,chargeTime)'...您還沒有分配'startHour'或'chargeTime' ...? –