When a decimal point is given, the Java program crashes, but int is used
When the user enters an integer, the program runs smoothly, but when the user enters the last decimal number, the program crashes
These are my mistakes:
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)
This is my code:
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
}
}
Solution
Integers recognize only integers If you want to be able to capture floating-point numbers, use float Parsefloat() or double parseDouble().
In order to make the answer more complete, let me give a simple example to explain why "4.", "4.0" and "4" are expressed in two different ways The first two are considered floating-point values (because Java only assumes that you mean 4.0). The way they are represented in memory depends largely on the data type you use to represent them - floating-point numbers or double precision numbers
Float uses single precision floating point standard to represent 4.0, while double means double precision floating point standard represents 4.0 Inter represents the value 4 in base-2 (so it's just 22)
Understanding how numbers are stored internally is the key to and development, not just Java In general, double is recommended because it provides a wider range of floating point numbers (and higher precision)
