0
//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");
}
luiza
  • 1
  • 2
  • When you parse a String to a number, the String must be in fact a string representation of a number, such as `1` or `2` or `25`. On the other hand, `"2 + 3"` is *not* a number but an equation, and this obviously won't parse. – Hovercraft Full Of Eels Jul 31 '21 at 11:46
  • If you need to parse a math expression in string form, then this is not so simple to do. Check out the answers to [this question](https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form) for more on this. – Hovercraft Full Of Eels Jul 31 '21 at 11:47

0 Answers0