开发者

null pointer exception [closed]

It's difficult to tell what 开发者_运维知识库is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.
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)); 
 } 

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜