扫描仪到JOptionPane编号(双)错误

时间:2013-05-23 00:55:17

标签: java java.util.scanner joptionpane

我正在尝试将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);
    }
  }

1 个答案:

答案 0 :(得分: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);