我有这个Person类,有一些方法可以添加,删除和查看你的朋友。出于某种原因,当我想查看我的朋友时,即使我认为我正在以正确的方式调用正确的方法,也会打印最后一个Person对象(即carl),而不管方法调用中的对象规范如何。有什么问题?
这是代码:
package person;
public class Person {
private static String name;
private static String friends;
public static void main(String[] args) {
Person ted = new Person ("ted");
Person jim = new Person ("jim");
Person todd = new Person ("todd");
Person tom = new Person ("tom");
Person carl = new Person ("carl");
// apparently I'm making a mistake here...
jim.addFriend(zack);
System.out.println(jim.getFriends());
}
public Person (String aName) {
name = aName;
friends = "";
}
public static void addFriend(Person friend) {
friends = friends + friend.name + " ";
}
public static void unFriend (Person nonFriend) {
friends = friends.replace(nonFriend.name + " ", "");
}
public static String getFriends () {
return friends;
}
}
答案 0 :(得分:3)
您正在使用静态变量。请试试这个。
package person;
public class Person {
private String name;
private String friends;
public static void main(String[] args) {
Person ted = new Person ("ted");
Person jim = new Person ("jim");
Person todd = new Person ("todd");
Person tom = new Person ("tom");
Person carl = new Person ("carl");
// apparently I'm making a mistake here...
jim.addFriend(zack);
System.out.println(jim.getFriends());
}
public Person (String aName) {
name = aName;
friends = "";
}
public void addFriend(Person friend) {
friends = friends + friend.name + " ";
}
public void unFriend (Person nonFriend) {
friends = friends.replace(nonFriend.name + " ", "");
}
public String getFriends () {
return friends;
}
}
答案 1 :(得分:0)
请
private static String name;
private static String friends;
要
private String name;
private String friends;
并通过删除static
public void addFriend(Person friend) {
friends = friends + friend.name + " ";
}
public void unFriend (Person nonFriend) {
friends = friends.replace(nonFriend.name + " ", "");
}
public String getFriends () {
return friends;
}