I thought this would be very easy but I am having problems searching nodes from a text file.
The data from the text file follows:
1
2
3
4
5
The data is being stored in the String “word”. They are numbers to avoid complexity.
Issue is- is that it keeps on returning false when calling the search method.
public class Search
{
static int count; // number of elements
Search ()
{
count = 0;
}
static void inputdata (Node head, Node node) throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
BufferedReader reader = new BufferedReader (new FileReader ("Words.txt"));
String word;
String line = null;
while ((line = reader.readLine ()) != null)
{
word = (line);
node = new Node (word);
node.next = head;
head = node; // need to set the new head of the list to the node that was just inserted
count++;
}
reader.close ();
node = head;
System.out.println ("Here is the list:");
System.out.println ();
do
{
System.out.println (node.data);
node = node.next;
}
while (node != null);
System.out.println ();
System.out.println ();
}
static boolean Found (String search, Node head, Node node) // recursive search method
{
boolean found;
Node temp; // sets a termpoary node to the head
node = head;
temp = head;
while (temp != null)
{
if (temp.data.equals (search))
return true;
temp = temp.next;
}
return false;
}
public static void main (String str[]) throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
DecimalFormat df = new DecimalFormat ("#");
//Search list = new Search (); //calls list via constructor
Node head = null;
Node node = null;
inputdata (head, node);
System.out.println (count + " entries");
String search, repeat;
System.out.println ();
System.out.println ("Which word do you want to search within the linked list?"); // returns true/false from a method
search = stdin.readLine ();
System.out.println (Found (search, head, node));
}
}
other file (class):
public class Node
{
Node next, prev;
String data;
public Node (String data)
{
this.data = data;
}
}
Your problem is that your linked list only ever has one object in it at a time, since you are always setting node.next to head, and head to node. Therefore, you will always only print the same number (which I am going to guess, is exactly what you’re seeing).
What you need to do is to fix your insertion routine. Something like this should do (mind you that it’s untested)