This is my BMI calculator with GUI. It compiles, but if the user enters characters rather than numbers into the fields, the program crashes. What is wrong with my catching of the numberformatexception? Id appreciate any help!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Exercise1b extends JFrame{
JLabel BMIlabel = new JLabel("Your BMI is ?");
JTextField height = new JTextField(10);
JTextField weight = new JTextField(10);
Exercise1b(){
super("BMI-calculator");
setLayout(new FlowLayout());
add(new JLabel("Enter your height in centimeters: "));
add(height);
add(new JLabel("Enter your weight in kilograms: "));
add(weight);
JButton button = new JButton("Calculate");
button.addActionListener(new CalculateListener());
add(button);
add(BMIlabel);
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class CalculateListener implements ActionListener{
public void actionPerformed(ActionEvent ave){
try {
double gotheight = Double.parseDouble(height.getText());
double gotweight = Double.parseDouble(weight.getText());
double userBMI = ((gotweight/(gotheight*gotheight))*10000);
BMIlabel.setText("Your BMI is " + (int)userBMI + " .");
}
catch (NumberFormatException exc) {
System.out.println("Not valid number");
}
//double gotheight = Double.parseDouble(height.getText());
//double gotweight = Double.parseDouble(weight.getText());
//double userBMI = ((gotweight/(gotheight*gotheight))*10000);
//BMIlabel.setText("Your BMI is " + (int)userBMI + " .");
}
}
public static void main(String[] args){
new Exercise1();
}
}