2014-02-24 46 views
0

我需要從用戶讀取文本並創建一個包含字符的數組,以便我可以通過FSM運行它們。但是,我似乎無法讓緩衝閱讀器同意非字符串類型的輸入。有什麼建議?我也不知道是否我應該使用數組的ArrayList將文件讀入char []數組或陣列列表

static ArrayList<Character> StringList = new ArrayList<Character>(); 
static char[] data; 
public static void main(String[] args){ 

    InputStreamReader ISR = new InputStreamReader (System.in); 
    BufferedReader BR = new BufferedReader(ISR); 
    try{ 
     String sCurrentChar; 
     while((sCurrentChar=BR.readLine())!=null){ 

      for(int i= 0; i<sCurrentChar.length(); i++) 
      StringList.add(sCurrentChar.charAt(i)); 


     } 
     for(int i =0; i<StringList.size(); i++){ 
      System.out.println(StringList.get(i)); 
     } 
    } catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 
+0

更好地使用char []而不是列表 – NFE

+0

可能的重複http://stackoverflow.com/questions/10006165/converting-string-to-character-array-in-java –

回答

0

也許像下面這樣可以爲你工作,如果你想讀原始字節的數據,也許以後使用它們作爲字符。這可能比一次讀取輸入行更好。

import java.io.DataInputStream; 
import java.io.EOFException; 
import java.io.IOException; 
import java.util.Arrays; 

public class a { 
    public static void main(String[] args){ 
    DataInputStream d = new DataInputStream(System.in); 
    int[] bytes = new int[256]; 

    try { 
     int b; 
     int l = 0; 
     while((b = d.readByte()) > 0) { 
     bytes[l++] = b; 
     if((l % 256) == 0) 
      bytes = Arrays.copyOf(bytes, (l + 256)); 
     } 
    } catch(EOFException e) { 
     // end-of-file 
    } catch(IOException e) { 
     System.err.println("AIEEEE: " + e); 
     System.exit(-1); 
    } 

    for(int i = 0; bytes[i] > 0; i++) System.out.print((char)bytes[i]); 
    System.exit(0); 
    } 
} 

陣列都在這裏治療的方法可能是一個很好的例子,一個人如何不應該做的,但話又說回來,這更多的是讀取數據的字節/無符號字符不是有效地處理數組。