2012-03-30 6 views
-2

Я просматриваю весь код. Я могу ввести простой .txt-файл для поиска слова. После того, как он просит слова, он возвращаетОтладка поисковой системы Java

Исключение в потоке "основного" java.lang.ArrayIndexOutOfBoundsException: -48 на SearchEngine.main (SearchEngine.java:150)

линия 150 является для (Int J = 0; J

Любая помощь отладки

Это основная поисковая программа, которая должна быть в состоянии найти файл .txt для любого слова

Назначение ссылка: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html

?.
import java.util.*; 
import java.io.*; 


public class SearchEngine { 


    //Counts the number of words in the file 
    public static int getNumberOfWords (File f) throws FileNotFoundException { 
     int numWords = 0; 
     Scanner scan = new Scanner(f); 
     while (scan.hasNext()) { 
      numWords++; 
      scan.next(); 
     } 
     scan.close(); 

     return numWords; 
    } 


    public static void readInWords (File input, String[] x) throws FileNotFoundException { 
     Scanner scan = new Scanner(input); 
     int i = 0; 
     while (scan.hasNext() && i < x.length) { 
      x[i] = scan.next(); 
      i++; 
     } 
     scan.close(); 
    } 

    public static String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException { 

     HashSet<String> distinctWords = new HashSet<String>(); 
     for(int i=0; i<x.length; i++){ 
      distinctWords.add(x[i]); 
     } 

     String[] distinctWordsArray = new String[distinctWords.size()]; 
     int i = 0; 
     for(String word : distinctWords){ 
      distinctWordsArray[i] = word; 
      i++; 
     } 


     return distinctWordsArray; 
    } 

    public static int getNumberOfLines (File input) throws FileNotFoundException { 
     int numLines = 0; 
     Scanner scan = new Scanner(input); 
     while (scan.hasNextLine()) { 
      numLines++; 
      scan.nextLine(); 
     } 
     scan.close(); 
     return numLines; 
    } 

    public static void readInLines (File input, String [] x) throws FileNotFoundException { 
     Scanner scan = new Scanner(input); 
     int i = 0; 
     while (scan.hasNextLine() && i<x.length) { 
      x[i] = scan.nextLine(); 
      i++; 
     } 
     scan.close(); 
    } 



    public static void main(String [] args) { 

     try { 

      //gets file name 
      System.out.println("Enter the name of the text file you wish to search"); 
      Scanner kb = new Scanner(System.in); 
      String fileName = kb.nextLine(); 
      String TXT = ".txt"; 
      if (!fileName.endsWith(TXT)) { 
       fileName = fileName.concat(TXT); 
      } 

      File input = new File(fileName); 

      //First part of creating index 

      System.out.println("Creating vocabArray"); 
      int NUM_WORDS = getNumberOfWords(input); 

      //Output the number of words in the file 
      System.out.println("Number of words is: " + NUM_WORDS); 


      String[] allWordsArray = new String[NUM_WORDS]; 
      readInWords(input, allWordsArray); 
      Arrays.sort(allWordsArray); 
      String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray); 

      //Output the number of distinct words 
      System.out.println("Number of distinct words is: " + distinctWordsArray.length); 
      System.out.println("Finished creating distinctWordsArray"); 

      System.out.println("Creating concordanceArray"); 
      int NUM_LINES = getNumberOfLines(input); 
      String[] concordanceArray = new String[NUM_LINES]; 
      readInLines(input, concordanceArray); 
      System.out.println("Finished creating concordanceArray"); 

      System.out.println("Creating invertedIndex"); 
      int [][] invertedIndex = new int[distinctWordsArray.length][10]; 
      int [] wordCountArray = new int[distinctWordsArray.length]; 


      int lineNum = 0; 
      while (lineNum < concordanceArray.length) { 
       Scanner scan = new Scanner(concordanceArray[lineNum]); 

       while (scan.hasNext()) { 
        //Find the position the word appears on the line, if word not found returns a number less than 0 
        int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next()); 

        if(wordPos > -1){ 
         wordCountArray[wordPos] += 1; 
        } 


        for(int i = 0; i < invertedIndex.length; i++) { 
         for(int j = 0; j < invertedIndex[i].length; j++) { 
          if (invertedIndex[i][j] == 0) { 
           invertedIndex[i][j] = lineNum; 
           break; 
          } 
      } 
      } 
       } 
      lineNum++; 
      } 
      System.out.println("Finished creating invertedIndex"); 

     System.out.println("Enter a word to be searched (type quit to exit program)"); 
     Scanner keyboard = new Scanner(System.in); 
     String searchWord = keyboard.next(); 
     while (!searchWord.equals("quit")) { 
      int counter = 0; 

         int wordPos = Arrays.binarySearch(allWordsArray, searchWord); 
       for (int j = 0; j<invertedIndex[wordPos].length; j++) { 
        if(invertedIndex[wordPos][j] != 0) { 
          int number = invertedIndex[wordPos][j]; 
          String printOut = concordanceArray[number]; 
                System.out.print(number); 
                System.out.print(" :"); 
                System.out.println(printOut); 
             } 
       } 

       }   



     } 
     catch (FileNotFoundException exception) { 
      System.out.println("File Not Found"); 
     } 

    } //main 
} //class 
+0

попробуйте задать вопрос. Как вы думаете, что означает ArrayIndexOutOfBoundsException? – j4y

+0

, когда они будут преподавать модульное тестирование в университетах? – Jayan

+1

Debuggin? В самом деле? - что находится в строке 150 вашего исходного кода? –

ответ

1

int wordPos = Arrays.binarySearch(allWordsArray, searchWord);

wordPos будет отрицательным, когда searchWord не в массиве. Поэтому

в for (int j = 0; j<invertedIndex[wordPos].length; j++) {, invertedIndex[wordPos] будет пытаться получить доступ отрицательный индекс массива, в вашем случае, -48

Вы должны сделать что-то вроде этого перед циклом:

if(wordPos < 0){ 
    // Do something 
}else { 
    for (int j = 0; j<invertedIndex[wordPos].length; j++) { 
    ... 
} 

Вы должны прочитайте Javadoc, особенно документ для returns. Вы получите ответ о -48.

Смежные вопросы