This is my full code:
import javax.swing.JOptionPane;
public class Lab5bug {
public static void main(String[] args) {
int x=0;
String str;
for (;;)
{
str = JOptionPane.showInputDialog("Enter a grade 0-100\n(Hit Cancel to abort)");
if (str==null || str.equals(""))
break;
x = Integer.parseInt(str);
if (x>=0 && x<=100)
break;
JOptionPane.showMessageDialog( null, "Invalid grade, try again");
}
if (str != null & !str.equals("")) //<===========BUG: NEEED TO USE &&
//&,||.| are all lead to bug if we press Cancel.
//str can be null it does not pass 1st condition
//but still pass 2nd condition
//str can be "" pass first condition but not second condition
//and therefre it still show the message The grade is 0
//But why
JOptionPane.showMessageDialog( null, "The grade is " + x);
}
}
When I run the program and press Cancel at the first dialog box, then the program returns a error:
Exception in thread "main" java.lang.NullPointerException
at Lab5bug.main(Lab5bug.java:19)
I have already located the problem, at this line if (str != null & !str.equals("")) But why only && works? I do not understand the logic behind this.
Replace
if (str != null & !str.equals(""))
with
if (str != null && !str.equals(""))
&
stands for bitwise AND. Therefore when str
is null, the expression !str.equals("")
throws a NullPointerException
. When the logical AND operator &&
is used, the !str.equals("")
expression won't be reached because the first condition str != null
is false.