0

I am getting a null pointer exception error when pressing the equals button on a simple Java calculator.

It's prob an easy fix...

I tried putting an if statement to check if string is empty, but that doesnt work. (Here's the code)

public class Calc {

    private JFrame frame;
    String buffer, operator;
    JTextField textField = new JTextField();

  
        JButton btnEquals = new JButton("=");
        btnEquals.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                double left = Double.parseDouble(buffer);
                double right = Double.parseDouble(textField.getText());
                textField.setText(compute(operator, left, right));
                operator = null;
                buffer = null;
                
            }
       });

    public static String compute(String operator, double left, double right) {
        if (operator != null) {
            switch (operator) {
                case "+":
                    return Double.toString(left + right);
                default:
                    return "ERR"; // Unsupported operator
            }
        }
        return "ERR"; // Operator was null
    }

}
  • Which line is the NullPointerException being attributed to? – MorganS42 Jul 10 '23 at 00:30
  • You never assign a value to `operator`. – shmosel Jul 10 '23 at 00:31
  • *I tried putting an if statement to check if string is empty,* - 1) that won't help since you are getting a NullPointerException. 2) we have no idea which string variable you are talking about. *It's prob an easy fix...* - probably, but since you haven't posted an [mre] like you were asked to do in your previous question we would only be guessing. – camickr Jul 10 '23 at 00:34
  • @camickr: its the Button btnEquals – user22190533 Jul 10 '23 at 00:38
  • That comment makes doesn't help. The ActionListener contains 5 statements. We have no idea which statement is causing the problem. Read your stack trace to find the statement, then find the variable from the statement that is null. We can't do this for you. – camickr Jul 10 '23 at 00:40
  • You declare `String buffer`, but never assign it a value, so it's always `null`. – John Bayko Jul 10 '23 at 00:43
  • I put `if(buffer!=null)`at start of the `btnEquals` Actionlistener, and deleted the `buffer=null` line, which seems to have remedied it (not sure if it the right fix, tho). – user22190533 Jul 10 '23 at 00:59
  • 1
    That "fix" will leave the buffer as null and your code will do nothing useful. More importantly, you seem to be "coding by guessing", writing code without any preexisting plan or forethought, and the most important thing for you at this stage is not to do that. Study your notes, and plan what you're going to write *before* you start writing it. – Hovercraft Full Of Eels Jul 10 '23 at 01:13

0 Answers0