我删除双向链表的播放器的代码工作正常,但System.out.print
语句不适用。
我在removeFirst和removeLast之前放置了System.outs.print
语句,因为我不知道输出在节点中删除的数据的方法,所以在删除之前将其打印出来。
我知道我目前的方法设计不好,但我不确定使用什么功能。
我在if语句中检查哪些条件以查看节点是否已成功删除?
else if (mChoice.startsWith("4")) {
System.out.println("What do you want to delete?");
mChoice = in.nextLine();
if (mChoice.contains("first")) {
System.out.println("Removed first player " + rBook.mHead.getData());
rBook.removeFirst();
}
else if (mChoice.contains("last")) {
System.out.println("Removed last player " + rBook.mHead.mPrev.getData());
rBook.removeLast();
}
else {
rBook.remove(rBook.searchByName(mChoice));
// System.out.println(rBook.get() + " removed."); this line
}
答案 0 :(得分:2)
我建议您修改remove()
函数以返回刚删除的元素。所以您正在查看的代码如下:
Player deleted = rBook.remove(rBook.searchByName(mChoice));
System.out.println(deleted.get() + " removed.");
答案 1 :(得分:2)
如果要存储列表中的哪些元素已被删除(例如,稍后打印或取消删除它们),那么更好的设计将是
哪种解决方案更好取决于您要解决的问题。
答案 2 :(得分:2)
如果您不想更改您的Player类及其功能,请尝试以下操作:
else if (mChoice.startsWith("4")) {
System.out.println("What do you want to delete?");
mChoice = in.nextLine();
Player deleted;
if (mChoice.contains("first")) {
deleted = rBook.mHead.getData();
rBook.removeFirst();
System.out.println("Removed first player " + deleted);
}
else if (mChoice.contains("last")) {
deleted = rBook.mHead.mPrev.getData();
rBook.removeLast();
System.out.println("Removed last player " + deleted );
}
else {
deleted = rBook.searchByName(mChoice);
rBook.remove(searchByName(mChoice));
System.out.println(deleted + " removed.");
}