2016-11-16 8 views
1

Ich versuche herauszufinden, wie man eine Liste von Strings in einer Textdatei liest und die Position des gefundenen Wortes zurückgibt. Ich bin mir nicht sicher, warum das nicht funktioniert. Kann mir jemand sagen, was ich falsch mache? Es gibt -1 für jedes Wort zurück und die Wörter sind definitiv da drin.Lineare Suche nach einem Wort im String-Array aus der Textdatei

public class LinearSearch extends SearchAlgorithm 
{ 
public int search(String[] words, String wordToFind) throws ItemNotFoundException { 
    for (int i = 0; i < words.length; i++) { 
     if (words[i] == wordToFind) { 
      return i; 
     } 
     else { 
      return -1; 
     } 
    } 
    return -1; 
} 

public final static String FILE_AND_PATH = "longwords.txt"; 
/* 
* TODO: Be sure to change the FILE_AND_PATH to point to your local 
* copy of longwords.txt or a FileNotFoundException will result 
*/ 


//Note how we deal with Java's Catch-or-Declare rule here by declaring the exceptions we might throw 
public static void main(String[] args) throws FileNotFoundException { 
    File file = new File("/Users/myName/Desktop/compsci/HOMEWORK/recursion/longwords.txt"); 
    Scanner input = new Scanner(file); 
    int wordCount = 0; 
    ArrayList<String> theWords = new ArrayList<String>(); 

    //read in words, count them 
    while(input.hasNext()) { 
     theWords.add(input.next()); 
     wordCount++; 
    } 

    //make a standard array from an ArrayList 
    String[] wordsToSearch = new String[theWords.size()]; 
    theWords.toArray(wordsToSearch); 

    //start with the linear searches 
    tryLinearSearch(wordsToSearch, "DISCIPLINES"); 
    tryLinearSearch(wordsToSearch, "TRANSURANIUM"); 
    tryLinearSearch(wordsToSearch, "HEURISTICALLY"); 
    tryLinearSearch(wordsToSearch, "FOO"); 
+1

Entfernen Sie auch Ihren 'else' Block ... oder Sie' -1 zurückgeben '(es sei denn das 'Wort' ist das erste Wort). –

+0

Oh ja, das war ein Unfall Ich habe es schon dankend entfernt. – iloveprogramming

Antwort

1

Sie können Strings nicht mit words[i] == wordToFind vergleichen. Sie müssen words[i].equals(wordToFind) verwenden.

Sie sollten auch den Else-Block innerhalb der for-Schleife entfernen.

0

Ihre Schleife kehrt bei der ersten Iteration zurück. Entferne den Else-Block.