2015-11-18 49 views
1

我有一個簡單的文本文件:陣列IndexOutOfBoundsException異常

John Jobs 225 Louis Lane Road 
Amy Jones 445 Road Street 
Corey Dol 556 The Road 

在那裏我有人們首先,姓氏和地址

我試圖分析它們是這樣的:

public void parseText() { 

     try { 
      File file = new File("test.txt"); 
      String[] splitted; 

      Scanner sc = new Scanner(file); 

      while (sc.hasNextLine()) { 
       String s = sc.nextLine(); 
       splitted = s.split("\\s+"); 
       System.out.println(splitted[0]); 
      } 
      sc.close(); 
     } catch (FileNotFoundException e) { 
      System.out.println("Error");  } 

    } 

splitted [0]正常工作,打印出人物的名字。 splitted [1]打印出姓氏,但給我一個IndexOutOfBoundsException。 spitted [2]打印出每個地址的第一個整數值,但又給我一個例外。

於是我試着這樣做:

String[] splitted = new String[4]; 

,並再次試圖比0訪問任何指數更大,但仍然有這個問題。 我在做什麼錯?

+0

您是否嘗試過調試?在「split」之前打印出「String s」,看看它實際得到了什麼。然後在分配它之後嘗試打印出'splited'數組。看看它顯示的是什麼 – 3kings

+1

嗯,它看起來是字符串s,是整個文本文件(當打印出來,在字符串拆分之前)。 – TopKek

+0

啊,所以你不能在每行後面的文件中有新的行字符 – 3kings

回答

0

這是你的文件的內容:

John Jobs 225 Louis Lane Road 
Amy Jones 445 Road Street 
Corey Dol 556 The Road 

當每一行被讀和拆分,splitted將包含第一次運行下一個運行6元和5。所以如果你不仔細使用索引,你顯然會得到IndexOutOfBoundsException

更好

的方法是使用foreach循環:

while (sc.hasNextLine()) { 
       String s = sc.nextLine(); 
       splitted = s.split("\\s+"); 
       //System.out.println(Arrays.toString(splitted)); 
       for (String string : splitted) { 
        System.out.print(string+" "); 
       } 
       System.out.println(); 
.....rest of code