空指针的问题
public class User implements Serializable {
private static final long serialVersionUID = -427838794924380991L;
private String password;
private String nickname;
private char sex;
private int head;
private String ip;
public User(String password, String nickname, char sex, int head) {
this.password = password;
this.sex = sex;
this.head = head;
if (nickname.equals("") || nickname == null) {
this.nickname = "无名";
} else {
this.nickname = nickname;
}
}
public User( String nickname, String password,String ip) {
this.nickname = nickname;
this.password = password;
this.ip=ip;
}
public void setIP(String ip){
this.ip=ip;
}
public String getIP(){
return ip ;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setSex(char sex) {
this.sex = sex;
}
public char getSex() {
return sex;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setHead(int head) {
this.head = head;
}
public int getHead() {
return head;
}
public ImageIcon getHeadIcon() {
ImageIcon image = new ImageIcon("images/" + head + ".png");
return image;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (head != other.head)
return false;
if (nickname == null) {
if (other.nickname != null)
return false;
} else if (!nickname.equals(other.nickname))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (sex != other.sex)
return false;
return true;
}
public String toString() {
return this.getClass().getName()
+ " pwd=" + this.password
+ ",nickname=" + this.nickname
+ ",head=" + this.head
+ ",sex=" + this.sex
+",ip="+this.ip
+ "]";
}
}
private User user;
user.setNickname(nickname);
红色部分总是说空指针问题,这是为什么啊?
[解决办法]
user = new User(); // 要new一下,就可以了!
[解决办法]
[解决办法]
User user = new User();
先创建对象,然后调用对象的方法
[解决办法]
private User user;
此时的user默认就是null
你等于是null.setName();
肯定是报错了!