2012-03-10 61 views
0

我的問題發生在for循環中,以便將文件中的值讀入我的分數數組中。該程序讀入並打印前6個值或2行的整數,但然後我得到ArrayIndexOutOfBoundsException:2將整數讀入多維數組

我不知道爲什麼這是停在那裏。如果我有j < 1000,它會讀取17個值。無論如何,我正在閱讀的文件在下面(不知道文本文件的格式)。

任何幫助,將不勝感激

Andy Matt Tom 

3 2  3 

4 4 5 

3 3 2 

2 2 2 

2 4 2 

2 3 2 

4 4 5 

2 3 3 

4 3 5 

3 3 6 

2 2 5 

3 3 3 

3 3 2 

3 2 4 

3 2 6 

3 4 3 

2 3 2 

2 2 2 

50 52 62 


public static void main(String args[]) 
{ 
    try 
    { 

    if (args.length<1) 
    { 
     System.out.printf("\n...You must enter the name of a file\n"); 
     System.exit(0); 
    } 

    Scanner infile = new Scanner (new File(args[0])); 


    int par= 3; 
    int play= 18; 
    String[] players= new String[play]; 
    int k=0; 
    int scores[][]= new int[play-1][par-1]; 

    while(infile.hasNext()) 
    { 
    players[k]=infile.next(); 

    k++; 

    if (k==play) 
    break; 
    } 


    for(int j=0; j<par; j++) 
    { 
     for (int i=0; i<play; i++) 
     { 
     scores[j][i]=infile.nextInt(); 
     System.out.println(scores[j][i]); 
     } 

    } 

    } 
    catch (FileNotFoundException e) 
    { 
    System.out.println("Bug"); 
    System.exit(0); 
    } 

} 

回答

0

其實,有三個問題。

  1. 只有3名球員,而不是18
  2. 你需要一個18x3陣列,而不是一個17x2陣列
  3. [i][j]而不是[j][i]

DIFF你的代碼對我的修改後的版本(這作品像一個魅力):

22c22 
<  String[] players= new String[play]; 
--- 
>  String[] players= new String[par]; 
24c24 
<  int scores[][]= new int[play-1][par-1]; 
--- 
>  int scores[][]= new int[play][par]; 
32c32 
<  if (k==play) 
--- 
>  if (k==par) 
41,42c41,42 
<   scores[j][i]=infile.nextInt(); 
<   System.out.println(scores[j][i]); 
--- 
>   scores[i][j]=infile.nextInt(); 
>   System.out.println(scores[i][j]); 
+0

非常感謝,我不知道我在想什麼-1 – mju516 2012-03-11 21:02:30

1
int scores[][] = new int [play-1][par-1]; 

爲什麼-1?這就是您的AIOOB來自哪裏。

1

這裏有兩個問題:

int scores[][] = new int[play-1][par-1]; // Why -1 ? 

和:

for(int j=0; j<par; j++)    // should be 'j < play' as 'j' 
             // is index to dimension 
             // with size 'play' 
{ 
    for (int i=0; i<play; i++)  // should be 'i < par' as 'i' is 
             // index to dimension with 
             // size 'par' 
    { 
     scores[j][i]=infile.nextInt(); 
     System.out.println(scores[j][i]); 
    } 
}