Reputation: 3
I get NullPointerException
when I press the CANCEL Option in my Swing.
Code:
while(!input.equals(CANCEL_OPTION));
And I get a message that it says incompatible types....
And here's my full code..
do
{
input=JOptionPane.showInputDialog("Enter a String.");
for(int i =input.length()-1;i>=0;i--)
{
result = result + (input.charAt(i));
disp.append("\n").append(result);
}
JOptionPane.showMessageDialog(null,input+"\n"+disp+"\n"+"\n"+result);
input="";
disp.setLength(0);
result="";
}
while(!input.equals(CANCEL_OPTION));
And the error code or something..
Exception in thread "main" java.lang.NullPointerException
at Reverse.main(Reverse.java:15)
Java Result: 1
Upvotes: 1
Views: 81
Reputation: 146
just use try catch statement..
try
{
do
{
//your codesss......
}
while(!input.equals(null));
}
catch(Exception ex)
{
////code..
}
hope it help.
Upvotes: 0
Reputation: 27356
Swap your do while
for a simple while
. The difference is, a do while
will run once, before it hits the test condition. Your code is receiving the CANCEL_OPTION
value which is null
, attempting to use it, then testing if it is null
. You need to move your test to the start.
Example
input=JOptionPane.showInputDialog("Enter a String.");
while(input != null) {
// Your code here.
}
NOTE: This will give the user the option to cancel should they wish to. If they do, it will skip processing the user input.
Upvotes: 0
Reputation: 51403
As the javadoc of JOptionPane.showInputDialog() states
Returns user's input, or null meaning the user canceled the input
if you want the user to enter something.
do {
input = JOptionPane.showInputDialog("Enter a String.");
} while (input == null); // user can't cancel
for (int i = input.length() - 1; i >= 0; i--) {
result = result + (input.charAt(i));
disp.append("\n").append(result);
}
....
Upvotes: 5
Reputation: 8657
When you press the cancel button the JOptionPane returns nothing, so your input is equal null. and you code will already enter the do scoop, and when your code reach the line :
for(int i =input.length()-1;i>=0;i--)
the input is already null.
i prefer to add after the that line the follwing:
if(input == null) {
break;
}
Upvotes: 0