根據你的意見...這應該做你在問什麼。你遇到的問題是,如果沒有外部條件的某種條件,你無法擺脫內部循環。
請注意,我將A
更改爲a
;變量不應該以大寫字母開頭。
int a[][] = new int[20][20];
int row = 0;
int col = 0;
int current = 0;
for (row = 0; row < a.length, current != -1; row++)
{
for (col = 0; col < a[row].length; col++)
{
try
{
current = scan.nextInt();
if (current == -1)
{
break;
}
else
{
a[row][col] = current;
}
}
catch (NoSuchElementException e)
{
System.out.println("I hit the end of the file without finding -1!");
current = -1;
break;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("I ran out of space in my 2D array!");
current = -1;
break;
}
}
}
我個人不會使用嵌套的循環,而走這條路線:因爲它是你插入相同數量爲每行每列,遍地
int a[][] = new int[20][20];
int row = 0;
int col = 0;
int current = 0;
while (scan.hasNextInt())
{
current = scan.nextInt();
if (current == -1)
{
break;
}
a[row][col] = current;
col++;
if (col == a[row].length)
{
row++;
col = 0;
if (row == a.length)
{
System.out.println("I ran out of space in my 2D array!");
break;
}
}
}
。你在做什麼? '將每個數字分配給2d數組中的一個不同的單元格'是有點模糊的。 –
我試圖用掃描儀從一個文件中讀取幾個值,並將每個數字插入一個單元格,直到讀取-1,while循環應該停止填充表格。 – Jim