【问题标题】:Having Issues With Arguments and Parameters In Methods方法中的参数和参数存在问题
【发布时间】:2019-03-31 22:23:45
【问题描述】:

我在最近的作业中遇到了这段代码的困难。该任务向用户显示汽油价格,询问他们想要什么类型以及多少加仑。该程序将总价格作为双倍返回。我在方法 calculatePrice 中创建了一个可以返回答案的开关。我无法收集该信息并以某种方式将其打印到方法 displayTotal。此外, displayTotal 必须是双精度数。任何帮助都将不胜感激。

public static double calculatePrice(int type, double gallons){

       switch (type){

      case 1:
        System.out.printf("You owe: %.2f" , gallons * 2.19);
        break;
      case 2: 
        System.out.printf("You owe: %.2f",  gallons * 2.49);
        break;
      case 3:
        System.out.printf("You owe: %.2f", gallons * 2.71);
        break;
      case 4:
        System.out.printf("You owe: %.2f", gallons * 2.99);
       }
    return type; 

     }

    public static void displayTotal(double type){


      System.out.println(type);


     }
   }

【问题讨论】:

  • 有什么问题?
  • 您需要将加仑和价格/加仑相乘的结果保存在一个变量中并返回。

标签: java drjava


【解决方案1】:

看起来像一个简单的错误 - 您从 calculatePrice 返回 type,而不是计算值:

return type;

您想要的是计算结果并返回该结果,而不是type。此外,如果您想先打印它,将其放入局部变量会有所帮助。示例:

public static double calculatePrice(int type, double gallons) {
    double result = 0;
    switch (type) {
        case 1:
            result = gallons * 2.19;
        break;
        case 2:
            result = gallons * 2.49;
        break;
        case 3:
            result = gallons * 2.71;
        break;
        case 4:
            result = gallons * 2.99;
    }
    System.out.printf("You owe: %.2f", result);
    return result;
}

【讨论】:

    【解决方案2】:

    您需要将加仑和价格/加仑相乘的结果保存在变量中并返回。

    public static double calculatePrice(int type, double gallons){
        switch (type) {
            case 1:
                return gallons * 2.19;
            case 2: 
                return gallons * 2.49;
            case 3:
                return gallons * 2.71;
            case 4:
                return gallons * 2.99;
         } 
    }
    
    public static void displayTotal(double type, double gallons){
        double totalPrice = calculatePrice(type, gallons);
        System.out.printf("You owe: %.2f", totalPrice);
    }
    

    【讨论】:

    • 感谢您的帮助。不幸的是,当我更改代码时,会收到错误消息,指出“break”是无法访问的语句。
    • 我很抱歉。我能够解决这个问题。非常感谢您的帮助!
    • 返回后中断是没有意义的——代码甚至无法编译。错误的答案。
    • @mvmn 我只是在编辑 OP 给出的代码。忘记删除了。放松一下,喝杯啤酒!
    • @Jusinr518 很高兴我能帮上忙。将此标记为未来读者的正确答案。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多