2013-01-10 55 views
0

這是我的代碼如下,我得到一個java.lang.IndexOutOfBoundsException &我無法修復它?我應該停止出現錯誤,因爲我在文件中有超過100個名字!限制陣列

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class ArrayPractice1 { 
    public static void main(String[] args) throws FileNotFoundException 
    { 

     String[] names = new String[100]; 
     Scanner scan = new Scanner(new File("names.txt")); 
     int index = 0; 

     while (scan.hasNext()){ 
      names[index]=(scan.nextLine()); 
      index++; 
     }  
     for(int i = 0; i <index -1; i++){ 
      System.out.println(names[i]); 
     } 

    } 

} 
+0

「ArrayList」在哪裏? – Mysticial

+0

是否有可能,names.txt文件包含多於100行? –

+0

您可以保存一個代碼行:names [index ++] =(scan.nextLine()); –

回答

0

你給100 array.If文件的大小超過100行,肯定會拋出異常

0

變化的條件在while循環

while (scan.hasNext() && index < 100)

這將停止讀取循環後,你填滿了陣列

2

你沒有與字符串ArrayList ,你正在處理一個簡單的字符串數組。 好像您選擇正從scan.hasNext() 100餘項,所以你最終嘗試訪問names[100],並得到例外您所描述
相反,你可以使用這個:

ArrayList<String> names = new ArrayList<String>(); 

然後

while (scan.hasNext()){ 
    names.add(scan.nextLine()); 
} 

並且您不必擔心事先知道確切的大小

1

如果輸入的大小在編譯時未知,請考慮使用usin g代替ArrayList而不是數組。

只需使用names.add(scan.nextLine())元素添加到ArrayList

ArrayList<String> names = new ArrayList<String>(); 
while (scan.hasNext()) { 
     names.add(scan.nextLine()) 
} 
+0

我的歉意!我忘了這是一個正常的陣列! – user1967788

0

爲什麼沒有把它獨立於任何上限?使用ArrayList

ArrayList<String> names = new ArrayList<String>(); 
    Scanner scan = new Scanner(new File("names.txt")); 

    while (scan.hasNext()){ 
     names.add(scan.nextLine()); 
    }  
    for(String name : names){ 
     System.out.println(name); 
    }