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

我试图弄清楚如何,或者是否可以调用一个包含参数的方法。我想在 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 called

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

}



慕勒3428872
浏览 195回答 3
3回答

RISEBY

如果要在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;}

杨__羊羊

你的代码应该像-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() 是一个参数化方法,并且您没有在其中提供任何参数。

慕盖茨4494581

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;    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java