-1
我試圖加載CSV文件到一個二維數組,但是當我去調用它主要我收到錯誤的線程未能爲.csv文件加載到二維數組
異常「主「java.lang.ArrayIndexOutOfBoundsException:0
在我的代碼,而該文件具有下一行,它分裂向上行,將其存儲在一個字符串數組這將反過來被移動到2D陣列。我不明白怎麼會有錯誤。任何人願意解釋還是我只是非常密集?
public int rows = 0;
public int cols = 0;
public String[][] filetable = new String[rows][cols];
public void set_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
if(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
cols = tokens.length;
rows++;
}
while(sc.hasNextLine())
{
rows++;
sc.nextLine();
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
public void to_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
int r = 0;
while(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
for(int c = 0; c < cols; c++)
{filetable[r][c] = tokens[c];}
r++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
問題可能是'filetable',但你永遠不會告訴我們'filetable'是如何設置的。另外,你說你用另一種方法來計算'cols',但你不讓我們知道那是什麼。底線:你沒有給我們足夠的信息來幫助你。 – ajb
對不起!現在就解決這個問題! – JAVANOOB
當你創建'filetable'時,'rows'和'cols'都是0,因爲'filetable'是在你的對象第一次構建時創建的。嘗試在計算'rows'和'cols'後分配'filetable = new String [rows] [cols];''。另外,您的方法需要兩次輸入整個輸入文件,這並不理想。使用'ArrayList'可以幫助您創建一個大小可以動態增長的數組,從而不必預先計算行數。 – ajb