I'm still at the beginner stage of learning Java and I'm currently having a problem in trying to re-enter the PIN code that I first entered to ensure that I entered it correct the second time. It's like setting up a passcode for your mobile device when I open it. Here's where the problem happens:
int firstSet, secondSet;
firstSet = Integer.parseInt(jTextField2.getText());
jTextField2.setText("");
jLabel1.setText("Re-Enter PIN");
secondSet = Integer.parseInt(jTextField2.getText());
if(firstSet==secondSet)
{
jLabel1.setText("PIN VERIFIED");
}
else
{
jLabel1.setText("PIN INCORRECT");
}
This is the error I'm getting:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
I hope that someone can help me. :)
You have the problem here
jTextField2.setText("");
// ...
secondSet = Integer.parseInt(jTextField2.getText());
You are setting the value of jTextField2.text
to ""
and when you try: secondSet = Integer.parseInt(jTextField2.getText());
you're getting an empty String
from .getText()
, so method Integer.parseInt()
is complaining with NumberFormatException
As pointed in the Integer:parseInt(String) API
Throws:
NumberFormatException
- if the string does not contain a parsable integer.
All this code is executed without interruption, so if you want to do this in this way with only one method call.
First delete this line:
jTextField2.setText("");
And use 2 text fields.
firstSet = Integer.parseInt(jTextField2.getText());
secondSet = Integer.parseInt(jTextField3.getText());
// ^ here!!!!
ADD-ON
In order to avoid similar problems when ueser enter non valid data, or no dagta at all I would recommend you to safe-parse the values of
try {
firstSet = Integer.parseInt(jTextField2.getText());
secondSet = Integer.parseInt(jTextField3.getText());
} catch (NumberFormatException e) {
jLabel1.setText("PIN NOT VALID; TRY AGAIN!!!");
}
ALTERNATIVE if you want to use same jTextField and ask user 2 times to repeat the PIN CODE
you must adapt your method in order to perform 2 actions:
Example
class YourClass {
int firstSet = 0; // global attribute!
public void yourListenerMethod() {
// if firstSet == 0 is first attempt
if (firstSet == 0) {
firstSet = Integer.parseInt(jTextField2.getText());
jTextField2.setText("");
jLabel1.setText("Re-Enter PIN");
//
// if firstSet != 0 is second attempt so compare
} else {
int secondSet = Integer.parseInt(jTextField2.getText());
if(firstSet==secondSet)
{
jLabel1.setText("PIN VERIFIED");
// reset the pin if necessary
firstSet = 0;
}
else
{
jLabel1.setText("PIN INCORRECT");
// reset the pin if necessary
}
}
}
}