【问题标题】:How do I use another method in a method?如何在方法中使用另一种方法?
【发布时间】:2019-09-27 15:05:39
【问题描述】:

我想在方法gesamtpreis()中使用方法preisProKilo()?它关于计算产品的总价格。 preis pro kilo = price per kilogesamtpreis = total amount

class Kaffeeladen {

  double preisProKilo(double grundpreis) {        
        return (grundpreis + 2.19) * 1.19;
  }

  double gesamtpreis(int gewuenschteMenge, double preisProKilo) {      
    return preisProKilo * gewuenschteMenge; 
    //Here its not using the method "preisProKilo" from above. 
  }

  public static void main(String[] args) {
    Kaffeeladen k = new Kaffeeladen();

    double preis1 = k.preisProKilo(3.00);
    System.out.println("Bei einem Grundpreis von 3,00 Euro kostet 1 kg Kaffee inklusive Steuern " + preis1 + " Euro.");


  }
}

【问题讨论】:

  • 尽管return 方式在gesamtpreis(int, double) 中不正确。无论如何,您都没有在代码中调用该方法。回报可能是这样的:return preisProKilo(preisProKilo)*gewuenschteMenge;

标签: java methods reference return


【解决方案1】:

您会感到困惑,因为您将方法和变量命名为相同的东西。不要这样做。

你根本没有调用方法,你只是在使用变量。

应该是这样的:

double preisProKilo(double grundpreis) {
    return (grundpreis + 2.19) * 1.19;
}

double gesamtpreis(int gewuenschteMenge, double newValueName) {
    return preisProKilo(newValueName) * gewuenschteMenge; 
}

您可以将newValueName的名称更改为您选择的任何名称,请尝试使用不同的名称。

此外,我没有看到您实际使用gesamtpreis(int, double) 的任何地方,因此您还需要通过在您的main 中执行以下操作来使用它:

Kaffeeladen k = new Kaffeeladen();
double value = k.gesamtpreis(2, 3.00);

【讨论】:

    【解决方案2】:

    您可能想给gewuenschteMenge 提供所需数量,grundpreis 提供gesamtpreis 或全价方法中的基本价格。

    class Kaffeeladen {
    
      double preisProKilo(double grundpreis) {        
            return (grundpreis + 2.19) * 1.19;
      }
    
      double gesamtpreis(int gewuenschteMenge, double grundpreis) {      
        return preisProKilo(grundpreis) * gewuenschteMenge; 
      }
    
      public static void main(String[] args) {
        Kaffeeladen k = new Kaffeeladen();
    
        double preis1 = k.preisProKilo(3.00);
        System.out.println("Bei einem Grundpreis von 3,00 Euro kostet 1 kg Kaffee inklusive Steuern " + preis1 + " Euro.");
    
    
      }
    }
    

    您实际上是在使用 preisProKilo 变量而不是调用方法 preisProKilo(double grundpreis) 来执行此操作,因此您必须按照上面的代码所示调用它。

    【讨论】:

      【解决方案3】:

      我不确定您在此处尝试做什么,因为变量的命名与方法名称相同,但要调用方法,您需要使用语法methodToCall(arg1, arg2)

      您似乎对方法的工作原理缺乏了解。一种思考方式是根据数学函数。例如,

      f(x)= x + 1
      

      如果x 为1,则f(x) 的值为2。如果x 为2,则f(x) 的值为3,依此类推。

      所以在 Java 中的写法如下:

      public int addOne(int x) {
        return x + 1;
      }
      

      要调用该方法,您需要这样做。

      public int doWork(int value) {
        // doing work...
        value = addOne(value);
        // doing more work...
        return value;
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-10
        • 1970-01-01
        • 2012-03-22
        • 2014-03-28
        • 1970-01-01
        • 2014-06-23
        • 2017-10-30
        • 1970-01-01
        相关资源
        最近更新 更多