これは非常に簡単だと思いましたが、テキストファイルからノードを検索するのに問題があります。
テキストファイルのデータは次のとおりです。
1
2
3
4
5
データは文字列「word」に保存されています。複雑さを避けるための数字です。
問題は、検索メソッドを呼び出すときにfalseを返し続けることです。
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));
}
}
他のファイル(クラス):
public class Node
{
Node next, prev;
String data;
public Node (String data)
{
this.data = data;
}
}