【问题标题】:Scanner to JOptionPane number (double) error扫描仪到 JOptionPane 编号(双)错误
【发布时间】:2013-05-23 09:24:27
【问题描述】:

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

【问题讨论】:

    标签: java java.util.scanner joptionpane


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2018-08-01
      • 1970-01-01
      • 2015-10-02
      • 2018-12-17
      • 2020-02-26
      相关资源
      最近更新 更多