2013-11-04 54 views
0

我已經編寫了讀取文件第三列(treeout1.txt)的代碼並將這些內容寫入另一個文件(tree.txt)中。現在我想打開tree.txt並編寫內容到stem.txt,其中tree.txt在每行中包含一個單詞並在每行的末尾找到一個分隔符。我在下面附加了該txt文件。您可以查看該文件以便更好地理解。現在,我想要將單詞寫入一行,直到找到分隔符「###」爲止...例如'女孩自己的紙'和下一行vol等等....我試過了,但是ArrayIndexOutOfBoundsException出現在[]中。爲什麼?以及如何解決這個問題?在java中處理ArrayIndexOutOfBoundsException

文本文件tree.txt下面

the 
girl 
own 
paper 
### 
vol 
### 
viii 
### 
no 
### 
@[email protected] 
### 
October 
@[email protected] 
@[email protected] 
### 
price 
one 
penny 
### 
as 
the 
baron 
have 
conjecture 
the 
housemaid 
whom 
he 
have 
call 
out 
of 
the 
nursery 
to 
look 
for 
### 
lons 
cane 
on 
find 
her 
master 
have 
go 
without 
it 
do 
not 
hurry 
back 
but 
stop 
talk 
### 

代碼給出:

package simple; 

import java.io.*; 
import java.util.Scanner; 
import java.util.StringTokenizer; 

public class Simple { 

    public static void main(String[] args) throws IOException { 
    String line; 
    String line2; 
    String[] a = new String[100]; 
    int i = 0; 
    try { 
     BufferedReader br = new BufferedReader(new FileReader("C:/TreeTagger/treeout1.txt")); 
     BufferedWriter output = new BufferedWriter(new FileWriter("D:/tree.txt")); 
     String separator = System.getProperty("line.separator"); 
     while ((line = br.readLine()) != null) { 
     StringTokenizer st2 = new StringTokenizer(line, "\n"); 
     while (st2.hasMoreElements()) { 
      String line1 = (String) st2.nextElement(); 
      String[] array = line1.split("\\s+", 3); 
      //System.out.println(array[2]); 
      output.append(array[2]); 
      output.newLine(); 
     } 
     } 
     output.close(); 
     br.close(); 
     BufferedReader br1 = new BufferedReader(new FileReader("D:/tree.txt")); 
     BufferedWriter out = new BufferedWriter(new FileWriter("D:/stem.txt")); 
     while ((line2 = br1.readLine()) != null) { 
     StringTokenizer st = new StringTokenizer(line2, " "); 
     while (st.hasMoreTokens()) { 
      String element = st.nextToken(); 
      System.out.println(element); 
      while (element != "###") { 

      a[i] = element; 
      i++; 
      } 
      out.append(a[i]); 
      element = element.replace(element, ""); 

     } 

     } 
    } catch (IOException e) { 

    } 
    } 
} 

回答

0

您需要重置i to 0找到###分隔符之後。否則,您將繼續增加i,直到它大於100(最大值爲a)。

此外,您不能在字符串上使用!=運算符(從您的代碼:element != "###")。您需要使用以下方法:

!"###".equals(element); 
+0

小號......我有一個正在重置我......不improvement..same錯誤即將 – saranya

+0

嘗試看看我的編輯,應該是'「###! 「.equals(element);'而不是'element!=」###「' –

+0

謝謝你......即使現在我得到錯誤......這是我的錯誤運行: 線程」main「java異常.lang.ArrayIndexOutOfBoundsException:100 \t在simple.Simple.main(Simple.java:55) Java結果:1 生成成功(總時間:1秒)僅第一字被讀 '的' – saranya

相關問題