2012-04-12 22 views
0

我剛剛學習Java並在Java中創建了自己的Word List和Word Node類。但是,我發現我的WordList索引方法總是返回-1。有人可以告訴我它有什麼問題嗎?它與使用掃描儀有關嗎? (我的教科書說這不是我的添加方法)。我的代碼如下(在它自己的文件中的每個類):Java列表節點無法找到已添加項目的索引

WordNode.java:

public class WordNode { 

private String value; 
private WordNode next; 

public WordNode(String newValue) { 
    value = newValue; 
    next = null; 
} 

public WordNode(String newValue, WordNode nextNode) { 
    value = newValue; 
    next = nextNode; 
} 

public String getValue() { 
    return value; 
} 

public WordNode getNextNode() { 
    return next; 
} 

public void setNextNode(WordNode node) { 
    next = node; 
}} 

WordList.java:

public class WordList { 
private WordNode first; 

public WordList(String firstNode) { 
    first = new WordNode(firstNode); 
} 

public void add(String newValue) { 
    first = new WordNode(newValue, first); 
} 

public void remove(String oldValue) { 
    if (first.getValue() == oldValue) { 
     first = first.getNextNode(); 
     return; 
    } 
    WordNode temp = first; 
    while (temp != null && temp.getNextNode().getValue() != oldValue) 
     temp = temp.getNextNode(); 
    if (temp != null) 
     temp.setNextNode(temp.getNextNode().getNextNode()); 
} 

public void moveToStart(String toMove) { 
    remove(toMove); 
    add(toMove); 
} 

public int indexOf(String item) { 
    WordNode temp = first; 
    int i = 1; 
    while (temp != null && temp.getValue() != item) { 
     temp = temp.getNextNode(); 
     i++; 
    } 
    if (temp == null) 
     return -1; 
    else 
     return i; 
} 

public String itemAtIndex(int index) { 
    WordNode temp = first; 
    int i = 1; 
    while (temp != null && i != index) { 
     temp = temp.getNextNode(); 
     i++; 
    } 
    if (i == index) 
     return temp.getValue(); 
    else 
     return ""; 
}} 

MTFencoder.java:

import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.PrintWriter; 
import java.util.Scanner; 

public class MTFencoder { 

public static void main(String[] args) { 
    try 
    { 
     Scanner scan = new Scanner(new FileReader(args[0])); 
     WordList dictionary = new WordList(scan.next()); 

     while (scan.hasNext()) { 
      String newWord = scan.next(); 
      int index = dictionary.indexOf(newWord); 
      if (index == -1) { 
       System.out.println("0 " + newWord); 
       dictionary.add(newWord); 
      } 
      else { 
       System.out.println(Integer.toString(index)); 
       dictionary.moveToStart(newWord); 
      } 
     } 
    } 
    catch (Exception ex) { 
     System.out.println("An error occured while reading the file. Check that it exists and is valid."); 
    } 
}} 

提前致謝。 Daniel

回答

1

在Java中,爲了檢查對象(包括字符串)是否相等,必須使用.equals方法。因此,在indexOf和remove中,您將不得不使用first.getValue().equals(oldValue)或類似的。

+0

謝謝!當然;我正在檢查引用而不是實際的字符串。 – dmos01 2012-04-12 05:55:42

相關問題