I am learning Java and I have been working on a problem for about 20 hours but I continue to get a NullPointerException. I do not believe it makes sense after reviewing Sun's Java Tutorial and my text books. I am trying to add two numbers from text fields as a simple calculator. I have programmed (multiply, divide and subtract) to visually read that the actions are occurring, which is ok; however, adding two numbers is causing the exception. My code is attached. Thanks for any assistance.
[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ] [ August 04, 2004: Message edited by: Dirk Schreckmann ]
You've made a mistake that everybody makes when they're starting out, but the good news is that nobody ever makes it twice
"Declaring" a variable means stating its type and name, with or without assigning a value to it. This declares a variable of type JFormattedTextField, and also assigns a value to it.
JFormattedTextField inputField2 = new JFormattedTextField();
This declares the variable without assigning a value to it:
This, on the other hand, doesn't declare anything; it just assigns a value to a previously declared variable:
inputField2 = new JFormattedTextField();
OK, now on to your problem. Variables declared at the top level of a class are "members" of that class, and can be accessed from all the member functions of a class. In contrast, variables declared inside a method are "local" to that method, and are only useable from within that one method.
You have declared two difference variables named inputField1 (and two more named inputField2). One set are members, and the other set are local to a constructor. You've initialized the ones that are local to the constructor, but the member ones are null. You see where I'm going with this: the members are null when the event handlers try to access them and get the entered text!
So, how to fix? Remove the type names from the declarations in the constructor, so that those lines become just assignments to the member variables instead of declarations of new local variables.