gpt4 book ai didi

java - 扫描仪到 JOptionPane 数字(双)错误

转载 作者:行者123 更新时间:2023-12-02 07:00:40 25 4
gpt4 key购买 nike

我正在尝试将 BMI 计算器程序从使用扫描仪转换为使用 JOptPane不过,当我出于某种原因将其带入 JOp 时,数字变得非常奇怪。使用扫描仪模式进行测试时,我使用 190 表示体重,使用 70 表示高度,得出的结果约为 27。

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

显然这是很遥远的事情,但我是 Java 新手,我真的不明白为什么..我能想到的最好的想法是,当我将字符串解析为 double 时,它会采用一些额外的字符格式,并将其与存储在字符串中的 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);
}
}

最佳答案

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

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

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

关于java - 扫描仪到 JOptionPane 数字(双)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com