为了账号安全,请及时绑定邮箱和手机立即绑定

调用带有参数的方法到另一个方法

调用带有参数的方法到另一个方法

慕勒3428872 2021-08-13 16:40:18
我试图弄清楚如何,或者是否可以调用一个包含参数的方法。我想在 costForPaint 方法中使用 requiredPaint 方法。(代码已简化):public class job {public static void main(String[] args) {    int rooms = 1;    double squareFeet = 0;    double totalSquareFeet = 115;    totalSquareFeet = squareFeet + totalSquareFeet;    }requiredPaint(totalSquareFeet);//i want to use the totalSquareFeet in this method, this is why it is calledpublic static double requiredPaint(double totalSquareFeet) {    double totalPaint = totalSquareFeet / 115;    return totalPaint;}public static double costForPaint() {    double paintCost = 2;    //shows error where required paint is    double totalPaintCost = requiredPaint() * paintCost;    return totalPaintCost;}
查看完整描述

3 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

如果要在costPaint方法中使用requiredPaint方法,则需要强制向 requiredPaint 方法发送双参数。现在这完全取决于您将如何实现您的功能。


您可以将 double 类型的参数添加到您的 costForPaint 方法中,如下所示:


public static double costForPaint(double totalSquareFeet) {


    double paintCost = 2;


    //shows error where required paint is

    double totalPaintCost = requiredPaint(totalSquareFeet) * paintCost;


    return totalPaintCost;

}


查看完整回答
反对 回复 2021-08-13
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

你的代码应该像-


public static double costForPaint() {


     double paintCost = 2;

     double totalPaint = 15;//any number you want to initialize in totalPaint 


     double totalPaintCost = requiredPaint(totalPaint) * paintCost;


     return totalPaintCost;

}

您收到错误是因为 requiredPaint() 是一个参数化方法,并且您没有在其中提供任何参数。


查看完整回答
反对 回复 2021-08-13
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

1> 在 Java 中,如果您已经向方法声明了一个参数,则必须传递该参数(空值或某个值)。这是一个可以根据您的要求完成的流程。


2> 你也不能在类块中调用方法。所以我删除了requiredPaint(totalSquareFeet);


public class job {

    public static void main(String[] args) {

        int rooms = 1;

        double squareFeet = 0;

        double totalSquareFeet = 115;

        totalSquareFeet = squareFeet + totalSquareFeet;

        costForPaint(totalSquareFeet);

    }


    //i want to use the totalSquareFeet in this method, this is why it is called

    public static double requiredPaint(double totalSquareFeet) {

        double totalPaint = totalSquareFeet / 115;

        return totalPaint;

    }


    public static double costForPaint(double totalSquareFeet) {


        double paintCost = 2;


        //shows error where required paint is

        double totalPaintCost = requiredPaint(totalSquareFeet) * paintCost;


        return totalPaintCost;

    }

}


查看完整回答
反对 回复 2021-08-13
  • 3 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信