此程序应该花费大量时间从用户手机充电并花费用户想要为手机充电的时间(索引0-23),并根据费率表示的费率返回费用。我遇到的问题是使用getChargeStartTime方法,该方法需要用户想要为手机充电的小时数,并找到以最低成本开始充电的最佳时间。我已经能够使每种方法都能单独工作,但事实证明这是让它们齐心协力的挑战。
这是程序应该做什么的一个例子(将使用下面的rateTable的值): 用户输入他们想要从索引4开始为手机充电3小时。然后,获取费用将转到索引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 );
}
}
答案 0 :(得分:0)
在您编写的代码中cost < minCost
是错误的。您希望在那里设置max cost
然后循环,以便该值以最低成本结束。
答案 1 :(得分:0)
这里不需要参数。您在方法中指定startHour
和chargeTime
的值,因此忽略您传入的值。
试试这个。
private int getChargingCost(){
String start = JOptionPane.showInputDialog(
"At what hour do you want to start charging your phone? (0-23)");
int startHour = Integer.parseInt(start);
String time = JOptionPane.showInputDialog(
"How many hours do you want to charge your phone?");
int chargeTime = Integer.parseInt(time);
...
}
并使用该方法的返回值,可能是
BatteryCharger obj = new BatteryCharger();
int cost = obj.getChargingCost();
另外,阅读“变量范围”的含义。
无法从main方法访问 chargeTime
,usercost
和bestStartHour
。
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 );
}