0

我正在尝试将 BMI 计算器程序从使用扫描仪转换为使用 JOptPane 虽然,当我出于某种原因将它带入 Jop 时,数字变得非常混乱。使用扫描仪模式进行测试,我使用 190 表示体重,70 表示高度,大约为 27。

但是,当我将此代码带入 JOp 时,相同的数字会产生大约 1.36

显然这很遥远,但我是 Java 新手,我真的不知道为什么.. 我能想到的最好的主意是,当我将字符串解析为双精度时,它会采用一些额外的字符格式并将其连接起来存储在字符串中的 ASCII 值完全改变了数字。

Double 中的“valueOf”和“parse”函数都给出了相同的结果,这至少是我得出的结论。任何人都可以帮忙吗?

import javax.swing.JOptionPane;

public class ComputeAndInterpretBMI

  {
    public static void main(String[] args)
    {

    /* //Original Code BloK --removed 22May2013;7892
    Scanner input = new Scanner(System.in);

    //prompt user to entier weight in #'s
    System.out.print("Enter weight in pounds: ");
    double weight = input.nextDouble();

    //prompt user to enter heigh in inches
    System.out.print("Enter hight in inches: ");
    double height = input.nextDouble();
    */

    //weight and height boxes
    String inputWeight = JOptionPane.showInputDialog ("Enter the weight in pounds");
    String inputHeight = JOptionPane.showInputDialog ("Enter the height in inches");
    //parse strings to doubles
    double weight = Double.valueOf(inputHeight);
    double height = Double.valueOf(inputWeight);

    final double KILOGRAMS_PER_POUND = 0.453359237; //THIS IS A CONST, NO TOUCH
    final double METERS_PER_INCH = 0.0254; //ANOTHER CONST, STILL NO TOUCH
    double weightInKilograms = weight * KILOGRAMS_PER_POUND;
    double heightInMeters    = height * METERS_PER_INCH;
    double bmi = weightInKilograms / (heightInMeters * heightInMeters);

    //Display the results here

    /*//Original code BloK --removed 22May2013;7892
    System.out.println("BMI is " + bmi);
        if (bmi < 18.5)
            System.out.println("underweight");
        else if (bmi < 25 )
            System.out.println("normal");
        else if (bmi < 30 ) 
            System.out.println("overweight");
        else
            System.out.println("obease");
    */
   String results;    

    if (bmi < 18.5)
       results = "underweight";
    else if (bmi < 25 )
       results = "normal";
    else if (bmi < 30 ) 
       results = "overweight";
    else
       results = "obease";

    String output = "BMI is :" + bmi + "\n" + results;

    JOptionPane.showMessageDialog(null, output);
    }
  }
4

1 回答 1

2

您在输入后将值分配给错误的变量;体重=身高,反之亦然:

// Your code:
double weight = Double.valueOf(inputHeight);
double height = Double.valueOf(inputWeight);

// Corrected code:
double weight = Double.valueOf(inputWeight);
double height = Double.valueOf(inputHeight);
于 2013-05-23T01:24:27.100 回答