When a user enters a whole number, the program runs smoothly, but when the user enters a number that has a decimal at the end, the program crashes.
These are the errors that I get:
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)
Here 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
}
}
An
Integeronly recognizes whole numbers. If you want to be able to capture floating point numbers, use eitherFloat.parseFloat()orDouble.parseDouble().To make the answer more complete, let me give you a quick example of why
"4.","4.0", and"4"are represented in two different ways. The first two are considered floating point values (since Java will just assume you mean4.0regardless), and how they are represented in memory depends heavily on which datatype you use to represent them – either afloator adouble.A
floatrepresents4.0using the single-precision floating point standard, whereas adoublewould represent4.0using the double-precision floating point standard. Anintrepresents the value4in base-2 instead (so it’d just be 22).Understanding how numbers are stored internally is critical and key to development, not just with Java. In general, it’s recommended to use
Doublesince that gives the larger range of floating point numbers (and higher precision).