2014-10-09 97 views
1

我是相當新的Java,我有一些代碼,這是不是很正常工作,我不知道爲什麼如此任何幫助將不勝感激。閱讀和存儲整數在陣列

我想從文本文件中讀取整數並將它們存儲在數組中。這裏是我的代碼:

Scanner keyboard = new Scanner(System.in); 

    File file = new File ("Grades.txt"); 
    FileReader input = new FileReader(file); 
    BufferedReader in = new BufferedReader(input); 

    int [] id = new int [500]; 

    String s = in.readLine(); 
    String s1 = s.substring(0,5); 

    while (s != null){ 
     int i = 0; 
     id[i] = Integer.parseInt(s1); 
     System.out.println(id[i]); 
     s = in.readLine(); 
    } 
    in.close(); 

我遇到的問題是,它記錄從文本文件中的第一個整數並顯示以下行相同的整數。這裏是我的輸出:

57363 
57363 
57363 
57363 
57363 
57363 
57363 

而且,這裏是文本文件,我正在讀的佈局:

57363 Joy Ryder D D C P H H C D 
72992 Laura Norder H H H D D H H H 
71258 Eileen Over C F C D C C C P 
70541 Ben Dover F F F P C C C F 
46485 Justin Time F C F C D P D H 
61391 Anna Conda D D F D D F D D 
88985 Bob Down P F P F P F P P 

回答

6

你一遍又一遍的覆蓋id[0]。您需要在循環中增加索引變量i。此外,s1從不更新。

int i = 0; 
while (s != null){ 
    id[i] = Integer.parseInt(s.substring(0, 5)); 
    System.out.println(id[i]); 
    s = in.readLine(); 
    i++;  
} 

一個更好的辦法但是要解決這個是使用Scanner

Scanner s = new Scanner(new File("Grades.txt")); 
int i = 0; 
while (s.hasNextLine()) { 
    id[i] = s.nextInt(); 
    System.out.println(id[i]); 
    // (The remaining fields could be read with s.next()) 
    s.nextLine(); // skip rest of line 
    i++; 
} 
+0

和a lso's1'永遠不會改變。 – Jesper 2014-10-09 08:17:20

+0

好點。更新了答案。 – aioobe 2014-10-09 08:19:05

+0

謝謝,第一個解決方案完美運作!我也嘗試過你提供的掃描器方法,因爲它看起來比較簡單,但輸出顯示單個數字0的7行重複 – AJJ 2014-10-09 09:25:20

1

你永遠不會改變S1,從來沒有增量I:

String s = in.readLine(); 
String s1 = s.substring(0,5); 

while (s != null){ 
    int i = 0; 
    id[i] = Integer.parseInt(s1); 
    System.out.println(id[i]); 
    s = in.readLine(); 
} 

我覺得這是你wnat什麼要做:

String s = in.readLine(); 
String s1 = s.substring(0,5); 
int i = 0; 
while (s != null){ 
    id[i] = Integer.parseInt(s1); 
    System.out.println(id[i]); 
    s = in.readLine(); 
    s1 = s.substring(0,5); 
    i++ 
}