加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

给小数点时,Java程序崩溃,但使用int

发布时间:2020-12-15 02:05:22 所属栏目:Java 来源:网络整理
导读:当用户输入整数时,程序运行平稳,但当用户输入最后有小数的数字时,程序崩溃. 这些是我得到的错误: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458) at java.lang.Integ
当用户输入整数时,程序运行平稳,但当用户输入最后有小数的数字时,程序崩溃.

这些是我得到的错误:

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

解决方法

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

为了使答案更加完整,让我举一个简单的例子说明为什么“4.”,“4.0”和“4”以两种不同的方式表示.前两个被认为是浮点值(因为Java只假设你的意思是4.0),它们在内存中的表示方式在很大程度上取决于你用来表示它们的数据类型 – 浮点数或双精度数.

float使用single-precision floating point standard表示4.0,而double表示使用double-precision floating point standard表示4.0.Inter表示base-2中的值4(因此它只是22).

了解数字如何在内部存储是关键和开发的关键,而不仅仅是Java.通常,建议使用Double,因为它提供了更大范围的浮点数(和更高的精度).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读