null pointer exception [closed]
package javajazzup;
public class LoginBean{
String loginid;
String pwd;
public LoginBean(){}
public String getLoginid(){
return loginid;
}
public void setLoginid(String loginid){
this.loginid = loginid;
}
public String getPwd(){
return pwd;
}
public void setPwd(String pwd){
this.pwd = pwd;
}
public String CheckValidUser(){
if(loginid.equals("JavaJazzUp") && pwd.equals("mypwd")){
return "success";
}
else{
return "fail";
}
}
}
You should change your method CheckValidUser() to:
public String CheckValidUser(){
if("JavaJazzUp".equals(loginid) && "mypwd".equals(pwd)){
return "success";
}else{
return "fail";
}
}
Testcase
public static void LoginBeanTest() {
LoginBean bean = new LoginBean();
bean.setLoginid("JavaJazzUp");
bean.setPwd("mypwd");
System.out.println(bean.CheckValidUser());
bean.setPwd("wrongpwd");
System.out.println(bean.CheckValidUser());
bean.setLoginid(null);
try {
System.out.println(bean.CheckValidUser());
catch (NullPointerException npe) {
System.out.println("NPE as expected");
}
bean.setLoginid("");
bean.setPwd(null);
try {
System.out.println(bean.CheckValidUser());
catch (NullPointerException npe) {
System.out.println("NPE as expected");
}
}
To get a null pointer
either loginid
is null
or pwd
is null
. It seems they are not set properly. But without providing more information we can't help you.
Your private member variables loginid
and pwd
are both initialized to null in your default constructor, since you don't do anything to set them to any default value. If you dereference either one without setting them to a non-null reference you'll get a NullPointerException
.
Try it like this:
package javajazzup;
public class LoginBean{
String loginid;
String pwd;
public LoginBean(String user, String password)
{
this.loginid = user;
this.pwd = password;
}
public LoginBean()
{
this("", "");
}
public String getLoginid(){
return loginid;
}
public void setLoginid(String loginid){
this.loginid = loginid;
}
public String getPwd()
{
return pwd;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
public boolean checkValidUser(String username, String password)
{
return (loginid.equals(username) && pwd.equals(password));
}
}
精彩评论