2013-08-30 43 views
0

我想讀的文本文件格式:Java的分隔符讀取文本文件

Array x 
1,3,5,4 

Array y 
12,13,15,11 

,並把它兩陣,但我只想整數。 我應該使用什麼分隔符來忽略字符串和空行?

這裏是我把代碼放在數組中。順便說一句,我用掃描儀讀取文件:

Scanner sc = null; 

    try 
    { 
    sc = new Scanner(new FileInputStream("C:\\x.txt")); 
    sc.useDelimiter(""); // What will I put inside a quote to get only the int values? 
    } 
    catch(Exception e) 
    { 
    System.out.println("file not found!"); 
    } 
int[] xArray = new int[4]; 
int[] yArray = new int[4]; 

    while (sc.hasNextInt()){ 
     for(int i=0; i<4; i++){ 
      xArray[i] = sc.nextInt(); 
     } 
     for(int i=0; i<4; i++){ 
      yArray[i] = sc.nextInt(); 
     } 
    } 

我想要得到的是

int[] xArray = {1,3,5,4} 
int[] yArray = {12,13,15,11} 

我希望你明白:)

感謝。

+0

爲什麼不使用'nextLine()'並使用'split'方法來解析每個'int'? –

+0

另外,在while的時候,你鬆散了第一個int在條件中讀取的同時(sc.hasNextInt()){ – azzurroverde

+0

明白了!感謝您的幫助。 – xpoiled7

回答

2

我建議你使用bufferedreader代替掃描儀。您可以使用以下代碼:

BufferedReader br=new BufferedReader(new FileReader("your file name")); 
br.readLine(); //it will omit first line Array x 
String x=br.readLine(); //it return second line as a string 
String[] x_value=x.split(","); //You can parse string array into int. 

這是針對Array x的。您可以對數組y執行相同的操作。之後解析爲int。

+0

明白了!謝謝! – xpoiled7

+0

@ xpoiled7如果通過接受答案得到了解決方案,請關閉此問題。 –

相關問題