当用户输入整数时,程序运行平稳,但当用户输入最后有小数的数字时,程序崩溃.
这些是我得到的错误:
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at BMI.main(BMI.java:11)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height; // declares the height variable
int weight; // declares the weight variable
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms"); // asks user for their weight
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters"); // asks user for their height
weight = Integer.parseInt(getweight); // stores their weight
height = Integer.parseInt(getheight); // stores their height
double bmi; // declares the BMI variable
bmi = weight / Math.pow(height / 100.0, 2.0); // calculates the BMI
double roundbmi; // variable to round the BMI to make it more read-able
roundbmi = Math.round(bmi); // rounds the BMI
JOptionPane.showMessageDialog(null, "Your BMI is: " + roundbmi); // displays the calculated and rounded BMI
}
}
Run Code Online (Sandbox Code Playgroud)
Mak*_*oto 16
一个Integer只能识别整数.如果您希望能够捕获浮点数,请使用Float.parseFloat()或Double.parseDouble().
为了使答案更完整,让我给你的,为什么一个简单的例子"4.","4.0"以及"4"在两种不同的方式表示.前两个被认为是浮点值(因为Java只是假设你的意思4.0),它们在内存中的表示方式在很大程度上取决于你用来表示它们的数据类型 - a float或a double.
A float表示4.0使用单精度浮点标准,而a double表示4.0使用双精度浮点标准.An int代表4base-2中的值(因此它只是2 2).
了解数字如何在内部存储是关键和开发的关键,而不仅仅是Java.一般来说,建议使用它,Double因为它提供了更大范围的浮点数(和更高的精度).