Java 程序在给出小数点时崩溃,但与 int 一起工作



当用户输入整数时,程序运行流畅,但是当用户输入末尾有小数的数字时,程序崩溃。

这些是我收到的错误:

    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)

这是我的代码:

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
  }
}

Integer只识别整数。 如果希望能够捕获浮点数,请使用 Float.parseFloat()Double.parseDouble()

为了使答案更完整,让我举一个简单的例子来说明为什么"4.""4.0""4"以两种不同的方式表示。 前两个被认为是浮点值(因为 Java 无论如何都会假设你的意思是4.0(,它们在内存中的表示方式在很大程度上取决于您用于表示它们的数据类型 - floatdouble

float表示使用单精度浮点标准的4.0,而double表示使用双精度浮点标准的4.0int表示以 2 为基数4的值(因此它只是 22(。

了解数字在内部的存储方式对于开发至关重要和关键,而不仅仅是使用Java。 通常,建议使用 Double因为这样可以提供更大的浮点数范围(和更高的精度(。

您正在解析不能有小数的Integers。 请尝试Double

您正在将输入解析为整数,其中不能包含小数点。您希望将其解析为双精度。

相关内容

最新更新