[英]How can I loop through a linked list and print each piece of data that matches the input?
I'm working on this method but am running into an issue.我正在研究这种方法,但遇到了问题。 When I enter a word that matches the data in an index of the linked list, it only prints the first index of the Linked List the same number of times that the word I entered appears in the entire linked list.
当我输入一个与链表索引中的数据匹配的单词时,它只打印链表的第一个索引,其次数与我输入的单词在整个链表中出现的次数相同。
public void iteratePrint(T aData) {
if (head == null) {
return;
}
//Typecast aData to string, and make it lowercase.
String a = (String)aData;
String strInput = a.toLowerCase();
//Create temp listnode to loop through.
ListNode temp = head;
//While temp is not null, check for match and if so, print.
while(temp != null) {
//Typecast temp.data into string (all of the data is a string anyway) and
//Make sure it is lowercase.
String b = (String)temp.data;
String strTemp = b.toLowerCase();
//This checks for the match and prints the current line.
//Not currently working
if(strTemp.contains(strInput)){
System.out.println(temp.getCurrent());
}
temp = temp.next;
}
}
For example: The linked list contains these as String data with their respective indices (balls bounce far, dogs play fetch with balls, my favorite toy is a ball).例如:链表包含这些字符串数据及其各自的索引(球弹得远,狗玩球,我最喜欢的玩具是球)。 If I enter my input as "ball", I would like it to print out as
如果我将输入输入为“球”,我希望它打印为
balls bounce far
dogs play fetch with balls
my favorite toy is a ball
However, it only prints out this:但是,它只打印出这个:
balls bounce far
balls bounce far
balls bounce far
Ball appears 3 times, and it is only printing out the first index of the linked list the amount of times that the input appears. Ball 出现 3 次,它只打印出链表的第一个索引输入出现的次数。
If strTemp.contains(strInput)
is not satisfied temp = temp.next;
如果
strTemp.contains(strInput)
不满足temp = temp.next;
will not get executed hence while loop will get stuck.不会被执行,因此 while 循环会卡住。 Take
temp = temp.next;
取
temp = temp.next;
outside of the if statement.在 if 语句之外。
I've solved the issue.我已经解决了这个问题。 The problem was with my
getCurrent()
method.问题出在我的
getCurrent()
方法上。 It was returning current.data
, when I needed to return my temp.data
.当我需要返回
temp.data
时,它正在返回current.data
。 Thanks to everyone who helped!感谢所有帮助过的人! I appreciate it.
我很感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.