//x^2 button
JButton button_x_mult_x = new JButton("x^2");
button_x_mult_x.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 20));
button_x_mult_x.setBounds(6, 125, 80, 50);
frmCalculator.getContentPane().add(button_x_mult_x);
button_x_mult_x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textField.getText().toString().trim();
float number = Float.parseFloat(text);
float x = number*number;
if(text.contains("+") || text.contains("-") || text.contains("x") || text.contains("/") == true){
textField.setText("Invalid input");
}
else if(text.equals("Invalid input") == true) {
textField.setText("0");
}
else {
textField.setText(String.valueOf(x));
}
}
});
...It doesn't work either else if.
Logically, when entering for example "2 + 3" we cannot use directly the x^2 button...and I get that error: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "2 + 3"
I tried to resolve the error with this if:
if (text.contains("+") || text.contains("-") || text.contains("x") || text.contains("/") == true){
textField.setText("Invalid input");
}