2016-11-21 54 views
0

編寫一個方法,在該文件中取一個文件,將文件中的前兩個元素作爲行和列,然後將剩下的作爲字符串並用它們填充二維數組。這是我的代碼到目前爲止,我不斷遇到一個越界異常。我應該在方法頭中引發異常。將文本文件輸入到2維數組中

public static String[][] input(String x) throws Exception{ 
    Scanner in=new Scanner(new File(x)); 
    String a =in.next(); 
    String b =in.next(); 
    int i = Integer.parseInt(a); 
    int j = Integer.parseInt(b); 
    String [][]table = new String[i][j]; 
    for(int count1=0;count1<table.length;count1++){ 
     for(int count2=0;count2<table[i].length;count2++){ 
      table[i][j] = in.next(); 
     } 
    } 
    return table; 

    } 

內容的文件:黑紅白藍橙 紅雀小熊盜紅人釀酒 第一第二第三第四第五 扎帕豪哈克特Metheny拉蒂默 上下左右 安德森切維厄特科文頓德里Highland_Heights Grateful_Dead創世紀網絡釣魚Van_der_Graaf_Generator是 耳眼口鼻咽喉

+0

你能顯示文件的內容嗎? –

+0

對不起,忘了補充吧。 – User42717

+0

謝謝大家的幫助 – User42717

回答

0

您正在使用ij而不是count1count2

替換for(int count2=0;count2<table[i].length;count2++){ => for(int count2=0;count2<table[count1].length;count2++){

table[i][j] = in.next(); =>table[count1][count2] = in.next();

結果代碼:

public static String[][] input(String x) throws Exception{ 
    Scanner in=new Scanner(new File(x)); 
    String a =in.next(); 
    String b =in.next(); 
    int i = Integer.parseInt(a); 
    int j = Integer.parseInt(b); 
    String [][]table = new String[i][j]; 
    for(int count1=0;count1<table.length;count1++){ 
     for(int count2=0;count2<table[count1].length;count2++){ 
      table[count1][count2] = in.next(); 
     } 
    } 
    return table; 

    } 
0

替換table[i][j] = in.next()table[count1][count2] = in.next()count2<table[i].lengthcount2<table[count1].length

for(int count1=0;count1<table.length;count1++){ 
    for(int count2=0;count2<table[count1].length;count2++){ 
     table[count1][count2] = in.next(); 
    } 
} 
相關問題