2013-04-01 107 views
0

我嘗試運行此代碼,此舉對前編碼器,但我得到這個異常:線程「main」 java.lang.ArrayIndexOutOfBoundsException數組索引越界異常JAVA

異常:0 (MTFencoder.java:10)

有人可以解釋爲什麼會發生這種情況嗎?

import java.io.FileReader; 
import java.io.BufferedReader; 
import java.util.StringTokenizer; 
import java.io.IOException; 

public class MTFencoder { 
    public static void main(String[] args) { 
     String filename = args[0]; 
     WordList wordList = new WordList(); 

     try { 
      String line; 
      BufferedReader br = new BufferedReader(new FileReader(filename)); 
      StringTokenizer st; 
      int index; 

      while ((line = br.readLine()) != null) { 
       st = new StringTokenizer(line); 

       while (st.hasMoreTokens()) { 
        String currentword = st.nextToken(); 

        if (wordList.hasElement(currentword)) { 
         index = wordList.Index(currentword); 
         wordList.remove(currentword); 
         wordList.add(currentword); 
         System.out.println(Integer.toString(index)); 
        } else { 
         wordList.add(currentword); 
         System.out.println("0" + currentword); 
        } 
       } 
      } 
     } catch (IOException e) { 
     } 
    } 
} 


class Node { 
    private String word; 
    private Node next; 

    public Node(String w) { 
     word = w; 
     next = null; 
    } 

    public String getWord() { 
     return word; 
    } 

    public Node getNext() { 
     return next; 
    } 

    public void setNext(Node n) { 
     next = n; 
    } 
} 


class WordList { 
    Node head; 

    public WordList() { 
    } 

    public void add(String w) { 
     Node n = new Node(w); 
     n.setNext(head); 
     head = n; 
    } 

    public int length() { 
     Node tmp = head; 
     int count = 0; 
     while (tmp != null) { 
      count++; 
      tmp = tmp.getNext(); 
     } 
     return count; 
    } 

    public boolean hasElement(String w) { 
     Node tmp = head; 
     while (tmp != null) { 
      if (tmp.getWord().equals(w)) return true; 
      tmp = tmp.getNext(); 
     } 
     return false; 
    } 

    public void remove(String w) { 
     if (!hasElement(w)) return; 
     if (head.getWord().equals(w)) { 
      head = head.getNext(); 
      return; 
     } 
     Node tmp = head; 
     while (!(tmp.getNext().getWord().equals(w))) tmp = tmp.getNext(); 
     tmp.setNext(tmp.getNext().getNext()); 
    } 

    public void dumpList() { 
     for (Node tmp = head; tmp != null; tmp = tmp.getNext()) 
      System.out.println(" >> " + tmp.getWord()); 
    } 

    public int Index(String w) { 
     int counter = 1; 
     Node temp = head; 
     while (!(temp.getWord().equals(w))) { 
      counter++; 
      temp = temp.getNext(); 
     } 
     return counter++; 
    } 
} 
+0

你如何運行這個程序? – prasanth

回答

4

該程序需要命令行參數。你沒有通過它。

程序需要按java MTFencoder fileyouwanttoprocess運行。您沒有傳遞文件名參數。

這是線10

String filename = args[0]; 

ARGS [0]是第一個命令行參數 - 您沒有傳遞命令行參數。

+0

現在正在工作。謝謝您的幫助! – user2230795