根据你的意见...这应该做你在问什么。你遇到的问题是,如果没有外部条件的某种条件,你无法摆脱内部循环。
请注意,我将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