2014-04-16 187 views
0

在爲BMI計算器做分配時,我一直遇到編譯器和正在使用的方法的問題。BMI計算器錯誤

該任務需要我調用函數double bmi來計算bmi。我在正確調用該函數時遇到問題。任何幫助都會很棒。

其中一個錯誤:

Prog5.java:44: error: illegal start of expression 
     public static double calculateBmi(double height, double total) { 
    ^

代碼:

import java.util.Scanner; 
public class Prog5 { 
    public static void main(String[] args) { 

    Scanner sc = new Scanner(System.in); 

    double avgweight,bmi,total,wReading; 
    int heightft,heightin,height,k; 
    String category,weightreading; 

    System.out.print("Enter the height(in feet and inches separated by spaces): "); 
    heightft = sc.nextInt(); 
    heightin = sc.nextInt(); 
    height = ((heightft*12)+heightin); 
    System.out.print("Enter the weight values separated by spaces followed by a  negative number: "); 
    wReading = sc.nextDouble(); 

    While (wReading >=0); 
    { 
     total = wReading+total; 
     Count++; 
     wReading = sc.nextDouble(); 
    } 

    avgweight = 0; 
    total = 0; 
    weightreading = "Weight readings: " + wReading; 
    avgweight = total/Count; 

    public static double calculateBmi(double height, double total) { 
     { 
      double bmi = 0; 
      double total = 0; 
      double height = 0; 
      bmi = (height*703)/(total*total); 
     } 
     return bmi; 
    } 

    if (bmi > 30) 
     category=("Obese"); 
    else if (bmi >= 25) 
     category=("Overweight"); 
    else if (bmi >= 18.5) 
     category=("Normal"); 
    else { 
     category=("Underweight"); 
    } 

    System.out.println(""); 
    System.out.println("Height: "+ heightft + " feet " + heightin + " inches"); 
    System.out.println("Weight readings: "+ count); 
    System.out.println("Average weight: " + avgweight + "lbs"); 
    System.out.println(""); 
    System.out.printf("BMI: " + "%.2f", bmi); 
    System.out.println(""); 
    System.out.println("Category: " + category); 
    System.out.println(""); 
} 

private static void ElseIf(boolean b) { } 
private static void If(boolean b) { } 

} 
+1

你不能在另一個方法的中間創建一個方法。 – BevynQ

回答

0

你的問題是,你正試圖定義一個方法中的方法(即公共靜態雙calculateBMi)(公共靜態void main),Java不會讓你這樣做。 (基本上,不是主要的方法需要附加到課程上。)

將來,您可能想在問這樣的問題之前環顧四周,因爲已經提出了這個問題的重複版本。你的問題基本上是:Function within a function in Java

+0

看着這個。謝謝。 – user3538183

1

你提到的問題是由於你在main內開始另一種方法。你反而想要一個像這樣的結構:

public class Prog5 
{ 
    public static void main(String[] args) 
    { 
     // code here 
    } 

    public static double calculateBMI(double height, double total) 
    { 
     //other code 
    } 
} 
+0

好吧我會試試這個。謝謝 – user3538183

+0

@ user3538183 ...然後你可以用'double someOutputVariable = calculateBmi(height,total);'main'裏面調用它('height'和'total'這裏是你的局部變量 - 沒關係什麼函數參數被命名)。 – Dukeling