2017-04-13 59 views
0

我必須在Java中爲一個任務創建一個身體質量指數計算器,並且如果用戶在要求重量時輸入字母字符,我希望程序退出並顯示一個信息。我需要幫助創建if語句。這是我的(這不工作)。我嘗試了各種其他的不平等符號,但沒有成功。我想我可能不得不使用一個if(在命令之間),但我沒有發現一種方法來使用權重變量的工作。當輸入一個字母字符時退出java程序

我收到該錯誤是如下 Lab4.java:21:錯誤不能找到符號 如果(重量< = Z) ^

public class Lab4 
    { 
      public static void main (String[] args) 
      { 
        Scanner kb = new Scanner (System.in); 
        System.out.println("enter e for english or m for metric"); 
        String choice; 
        choice = kb.nextLine(); 
        char firstchar; 
        firstchar = choice.charAt(0); 
      boolean english; 
      english = firstchar == 'e'; 
      if (english) 
      { 
        // prompt the user to input their weight in pounds 
        System.out.println("Enter your weight in pounds"); 
        double weight = kb.nextDouble(); 
        if (weight <= Z) 
        { 
          System.out.println("letters are not an acceptable weight"); 
          System.exit(0); 
        } 
        // prompt the user to input their height in inches 
        System.out.println("Enter your height in inches"); 
        double height = kb.nextDouble(); 
        if (height == 0.0) 
        { 
          System.out.println("0 is not a valid height"); 
          System.exit(0); 
        } 
        // make bmi to an integer and compute bmi by dividing weight by height^2 * 750 
        int bmi = (int)(weight/(height*height)*703); 
        // have the computer display height, wieght, and bmi 
        System.out.printf("your weight is %8.2f", weight); 
        System.out.println(" pounds"); 
        System.out.printf("your height is %8.2f", height); 
        System.out.println(" inches"); 
        System.out.println("your BMI is " + bmi); 
        if (bmi <= 24) 
          System.out.println("Normal Bodyweight"); 
          else 
          { 
            if (bmi > 30) 
              System.out.println("Obese"); 
            else 
              System.out.println("Overweight"); 
+0

請包含更多上下文,特別是您的變量聲明和錯誤消息。 – shmosel

+0

「錯誤找不到符號if(weight <= Z)」。那是因爲「Z」沒有被定義。 –

回答

1

如果weight是輸入字符串。您可以使用以下函數的isAlpha函數:https://stackoverflow.com/a/5238524/1926621

然後執行if (isAlpha(weight))作爲檢查輸入是否按字母順序排列的條件。

+0

@OusmaneMahyDiaw:謝謝你讓我知道!刪除代碼,保留源代碼鏈接,以供參考。 – Mohit

+0

不客氣:)。 –

0

考慮weight是字符串 -

if(!weight.matches("[-+]?\\d*\\.?\\d+")){ 
    System.out.println("Ikke akseptert. Quitter"); 
    System.exit(0); 
} 
1

在代碼中,你正在使用kb.nextDouble()這將引發InputMismatchException,程序將被終止閱讀weightdouble即使在執行/輸入你if檢查(即weight <= Z前)。

此外,一個更重要的一點是,你不能char類型比較double直接即像weight <= Z

所以,讀weight如使用scanner.nextLine()字符串,如下圖所示,然後檢查,如果它不包含字母(使用正則表達式),如下所示:

String weight = kb.nextLine(); 
if(!weight.contains(/^\d*\.?\d*$/)) { 
    System.out.println("letters are not an acceptable weight"); 
    System.exit(0); 
} 
相關問題