![](/img/trans.png)
[英]How to use variables initialized in one method into another method in another class
[英]How to get variables from one static method and use them in another method
我正在嘗試使用名為 getBMI 的靜態方法中的變量:
public static double getBMI(int weightKG, int heightCM)
{
Scanner input = new Scanner(System.in);
// Input Weight
System.out.print("Enter your weight in kilograms: ");
weightKG = input.nextInt();
System.out.println();
// Input Height
System.out.print("Enter your height in centimeters: ");
heightCM = input.nextInt();
System.out.println();
return heightCM;
return weightKG;
}
並在另一個名為 calculateMetricBMI 的靜態方法中使用它:
public static void calculateMetricBMI()
{
getBMI();
System.out.println("A body mass index of 20-25 is considered \"normal\"");
double bmiMetric = weightKG/Math.pow(heightCM/100.0, 2);
System.out.print("Your BMI is " + bmiMetric);
}
但是,嘗試 getBMI() 時出現錯誤; 在calculateMetricBMI中。
編輯:
決定給getBMI()添加參數; 現在它顯示 getBMI(int weightKG, heightCM);
但是我收到這個錯誤:
'.class' 預期
';' 預期的
';' 預期的
需要意外類型:找到的值:類
你得到一個錯誤,因為你在調用 getBMI() 時沒有參數,它需要調用 2 個整數。
您也不能從 1 個方法返回 2 個變量。
嘗試這個:
public static void calculateMetricBMI() {
double weightKG = getWeight();
double heightCM = getHeight();
System.out.println("A body mass index of 20-25 is considered \"normal\"");
double bmiMetric = weightKG/Math.pow(heightCM/100.0, 2);
System.out.print("Your BMI is " + bmiMetric);
}
public static double getWeight() {
Scanner input = new Scanner(System.in);
// Input Weight
System.out.println("Enter your weight in kilograms: ");
double weightKG = input.nextInt();
return weightKG;
}
public static double getHeight() {
Scanner input = new Scanner(System.in);
// Input Height
System.out.println("Enter your height in centimeters: ");
double heightCM = input.nextInt();
return heightCM;
}
在你的主要電話中
calculateMetricBMI();
這是一個非常多余的解決方案,您始終可以只要求在 calculateMetricBMI() 中輸入,而不必調用其他 2 個方法。
您不能在一個方法中同時返回兩個值。 但是,我更改了您的代碼以直接返回計算結果。
如果您要在其中初始化它們,則您的方法不需要參數。 只需在您的方法中創建它們。
如果你願意使用帶參數的方法,當你調用該方法時,你當然應該使用參數
getBMI()
在這里不起作用,例如您應該調用getBMI(50.0, 165.0)
但這是一個糟糕的例子,因為它無論如何都不起作用。
看看下面的代碼,它更清晰,會讓你得到更好的結果。
public static double getBMIMetric()
{
Scanner input = new Scanner(System.in);
// Input Weight
System.out.print("Enter your weight in kilograms: ");
int weightKG = input.nextDouble();
System.out.print("Enter your height in centimeters: ");
int heightCM = input.nextInt();
System.out.println();
return weightKG/Math.pow(heightCM/100.0, 2);
}
public static void calculateMetricBMI()
{
System.out.println("A body mass index of 20-25 is considered \"normal\"");
double bmiMetric = getBMIMetric();
System.out.print("Your BMI is " + bmiMetric);
}
你需要調用getBMI();
有兩個參數。
此外,您不能返回 2 個不同的變量,盡管這可能會導致語法錯誤。
另一件需要注意的事情是你需要保存getBMI();
正在送你。
例如: int weightKG = getBMI()
和getBMI()
應該只返回一個值,而不是您在代碼中描述的兩個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.