java登录引发NullPointerException
我正在试验Java登录方法。有人能给我解释一下为什么我会得到这个空点异常吗java登录引发NullPointerException,java,eclipse,nullpointerexception,Java,Eclipse,Nullpointerexception,我正在试验Java登录方法。有人能给我解释一下为什么我会得到这个空点异常吗 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Remote implements ActionListener { Action action; Gui gui; String output; Boolean result; public Remot
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Remote implements ActionListener {
Action action;
Gui gui;
String output;
Boolean result;
public Remote(Gui g, Action a) {
action = a;
gui = g;
actionListenerMeth(this);
}
@Override
public void actionPerformed(ActionEvent arg0) {
try {
String a = gui.username_tf.getText();
char[] c = gui.password_tf.getPassword();
String b = new String(c);
result = action.login(a, b);
} catch (Exception ee) {
ee.printStackTrace();
}
if (result == true) { //<--this is where Eclipse shows me the error ...
output = "You are Successfuly Loged In!";
} else {
output = "Username or Password is Wrong!";
}
gui.result_lb.setText(output);
}
public void actionListenerMeth(ActionListener ae) {
gui.login_bt.addActionListener(ae);
}
}
}看起来像
action.login(a,b)代码>返回null
因此,在您的例子中,布尔对象null
应该与原语false
进行比较。
因此,null
将使用boolean.booleanValue()
转换为一个基元boolean
,它给出一个NullPointerException
所以你必须改变:
if (result == true)
到
您将result
声明为Boolean
对象,而不是Boolean
原语。当执行if(result==true)
时,VM尝试使用result
上的方法调用将result
转换为布尔基元,该方法调用为null
解决方案:将结果
设置为布尔值。这将隐式初始化为false
顺便说一句,您不需要说if(result==true)
,您只需要说if(result)
,在使用box typeBoolean
之前您需要学习。错误来自box typeBoolean
等于unbox type布尔值true或false。如果使用box type,则代码应为
Boolean result;
if (result != null)
或者,如果您使用unbox类型,您的代码应该是
boolean result;
if (result == true) {//TODO}
实际上,ubox布尔值不需要==
。你可以这样申报
if (result){//DO SOMETHING}
action.login做什么?第29行是哪一行?该行中有空值:nova.Remote.actionPerformed(Remote.java:29)
如果在If(result==true)
中抛出异常,则表示action.login(a,b)==null
显示您的login
methodTrue,但是大概OP不认为login
应该返回空值。问题是有人能解释一下为什么我会得到这个空值异常
答案是正确的“解决方案:将结果设为布尔值”。不。。。这只会导致异常抛出到另一行。此代码存在一些问题,但提出的具体问题与将null对象转换为基元有关。这不是解决方案。问题是login
返回的Boolean
为空。是的,因为即使gui.username\u tf.getText()
抛出异常,result
仍然是一个值为false的有效原语(或者,因为它是一个实例变量,无论上次是什么-它实际上应该是一个局部变量). 测试if(result)
将计算为false,而不是抛出一个NPE。但是,yes-action.login应该返回一个基元或非null布尔值。就像我说的,这个代码还有其他问题。你说得对,谢谢!如果(结果){//…}
足够的话,就必须从布尔值改为布尔值。我是新来的,我正在学习:)
boolean result;
if (result == true) {//TODO}
if (result){//DO SOMETHING}