我的一段代码触发了一个无限的 while 循环,我不确定为什么。我以前在同一个程序中使用循环本身将 friend 添加到链接列表并且它工作正常,所以我不明白为什么它现在变成了无限循环。
while (!a.equals("*")){
curr = friendlist.getUsers().getFront();
while (curr!=null){
if (curr.getData().getName().equals(a)){ //why is it not removing friends?
d.removeFriend(curr.getData());
}
curr = curr.getNext();
}
System.out.println("Add a friend by typing in their name. Enter * to end. ");
a = in.nextLine();
}
以上代码从另一个类访问以下段:
public void removeFriend(User u){
if (friendsList.isEmpty()){
System.out.println("Empty list, cannot remove.");
}
else{
Node c = friendsList.getFront();
while (c.getNext()!=null){
if (c.getNext().getData().equals(u)){ //condition: if the data is the same
c.setNext(c.getNext().getNext()); //change the link
c.getNext().setData(null); //set the next data to null (cut the link)
friendsList.setSize(friendsList.size()-1);
c = c.getNext();
}
}
}
}
为什么代码运行不正常?
最佳答案
正如另一位发帖人所提到的,您在一个代码块中两次调用了 getNext()
方法。
我认为这是适合您的方法
while (c!=null){
if (c.getNext().getData().oldestFriend().getBirthYear()>c.getData().oldestFriend().getBirthYear()){
a = c.getNext().getData();
continue; //then skip the current iteration, so that your line below after the if statement, wont get called.
}
c = c.getNext();
}
你为什么不这样做,因为现在看起来你正在调用同一个方法三次!
相反,将从 getNext()
返回的任何内容存储到一个变量中,然后访问该局部变量并用它做任何你想做的事情,分析是你喜欢的等等。
关于java - 循环变成无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763757/