0

I just started to try and learn Java and in making a program to practise I have run into an issue and was hoping smoeone could help me.

I'm sure it is something very basic but I can't spot it.

I have a '+' button that when clicked add the value of a text field into an integer variable.

Below is the code:

   private void cmdPlusActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        intTotal=intTotal + Integer.parseInt(txtDisplay.getText());
    }   

I get a whole bunch of errors like below:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

I thought maybe what I was doing to convert the text into integer was wrong, but even if I replace with something like:

intTotal=intTotal + 1;

It gives me the same error so I'm not sure what I am doing wrong.

Madushan Perera
  • 2,528
  • 1
  • 15
  • 30
Kahn Mun
  • 23
  • 1
  • 6
  • Is intTotal an int or an Integer? The only away I can see "intTotal=intTotal + 1;" to throw an NPE is if intTotal is an uninitalized Integer. Save yourself many headaches and use primitives (int, long, double, ...) instead of their wrapper counterparts (Integer, Long, Double, ...) whenever possible. – Jose Ferrer Dec 13 '15 at 18:48
  • Reimeus: Thanks for the link. I did search before I asked but I searched for "adding two integers" and didn't search for the error. Jose: Thanks. I saw your response first and simply changing from Integer to Int solved it. Now I followed Reimeus's link and understand what I did wrong and how it works. Thank you both! – Kahn Mun Dec 13 '15 at 18:57

0 Answers0