[英]“JOptionPane java.lang.NullPointerException” error in Java
这是我的完整代码:
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);
}
}
当我运行程序并在第一个对话框中按“取消”时,程序将返回错误:
Exception in thread "main" java.lang.NullPointerException
at Lab5bug.main(Lab5bug.java:19)
如果(str!= null和!str.equals(“”))在这一行,我已经找到了问题,但是为什么只有&&有效? 我不了解其背后的逻辑。
&
不会使语句短路,这意味着如果str != null
为false,它仍会尝试str.equals("")
,如果str
为null则将导致NPE。 即使第一部分为假&
也会用&
天真地评估语句的第二部分。
&&
之所以起作用是因为它使语句短路,并且如果str != null
为false,则它会从该语句中断,而不是评估该语句的第二部分并避免使用NPE; 因为如果第一个值为false,则该语句不能为true。
大多数情况下, &&
比&
更可取。
同样的规则也适用于OR |
和||
。 true | throw new RuntimeException("Second part of statement was evaluated ");
将抛出该异常,而true || throw new RuntimeException("Second part of the statement was evaluated")
true || throw new RuntimeException("Second part of the statement was evaluated")
将不会到达异常,因为该语句的第一部分评估为true,从而保证该语句为true,因此会短路并中断该语句。
更换
if (str != null & !str.equals(""))
与
if (str != null && !str.equals(""))
&
代表按位与。 因此,当str
为null时,表达式!str.equals("")
抛出NullPointerException
。 使用逻辑AND运算符&&
,将不会达到!str.equals("")
表达式,因为第一个条件str != null
为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.