2013-04-06 42 views
1

現在我有這樣的錯誤:在線程 「主要」 java.lang.ArrayIndexOutOfBoundsException讀取文件從電腦

例外:4 在Lotto1.main(Lotto1.java:37)

37號線:arr [count] [0] = s.next()+「」+ s.next();

import java.io.*; 
import java.util.*; 

public static void main(String[] args) throws IOException { 

     File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt"); 
     Scanner s; 
     try { 
      s = new Scanner(f); 

      BufferedReader reader = new BufferedReader(new FileReader(f)); 
      int lines = 0; 
      while (reader.readLine() != null) { 
       lines++; 
      } 
      reader.close(); 

      arr = new String[lines][3]; 

      int count = 0; 
      //while theres still another line 
      while (s.hasNextLine()){ 
       arr[count][0] = s.next() + ""+ s.next(); 
       arr[count][1] = s.next(); 
       arr[count][2] = s.next(); 
       count++;     
      } 
     } catch (FileNotFoundException ex) { 
      System.out.println("File does not exist"); 
     } 
+1

將文件放在同一個文件夾,從你在哪裏運行代碼或將文件傳遞給文件讀取器而不是文件的名稱......所以'BufferedReader reader = new BufferedReader(new FileReader(f));' – 2013-04-06 17:46:46

+0

你爲什麼要讀取看起來像相同的文件兩次,並以兩種不同的方式(掃描儀和FileReader)? – 2013-04-06 17:50:14

+0

@PaulGrime從技術上講,他試圖讀取一個並打開另一個:D – 2013-04-06 17:50:54

回答

2

你沒有把正確的路徑進入的FileReader只進文件F,你可以通過˚F到的FileReader而不是重複的路徑:

File f = new File("D:\\database_lotto.txt"); 
[...] 
BufferedReader reader = new BufferedReader(new FileReader(f)); 
+0

我改變了它現在我有另一個錯誤:線程「main」java.lang.ArrayIndexOutOfBoundsException中的異常:4在Lotto1.main(Lotto1.java:37) 37行:arr [count] [0] = s.next() +「」+ s.next(); – user1831131 2013-04-06 18:08:27

+0

每次調用「s.next()」時,都會導致內部的「line-index」可能導致錯誤,您應該只在每次調用「s.next() – 2013-04-06 18:11:47

+0

我改了它,仍然是同樣的問題:( – user1831131 2013-04-06 18:19:28