2017-01-23 46 views
-1

该程序应该花费小时从用户手机充电,并花费用户想要为手机充电的时间(索引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); 

      } 
     } 
+0

'obj.getChargingCost(startHour,chargeTime)'...您还没有分配'startHour'或'chargeTime' ...? –

回答

0

在你所编写的代码cost < minCost是错误的。您想在那里设置max cost,然后循环,以便该值以最低成本结束。

0

这里不需要参数。您在该方法内指定startHourchargeTime的值,因此忽略您通过的值。

请尝试此操作。

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(); 

此外,对什么是“变量范围”的意思阅读起来。

chargeTime,usercostbestStartHour无法从主要方法访问。

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); 

     }