2011-09-18 82 views
2

我是Java新手,一般编程。我最近开始使用数组,并且在本书中进行了一次练习,我认为id会试一试。目标是使用扫描器类读取文件,将每个数字分配给2d阵列中的不同单元。这是我的方法。但不管我如何改变它,我似乎不能得到理想的结果。要么我最终得到每个单元格中的最后一个数字,要么我得到一个错误。请帮忙。通过扫描仪更新2d阵列

int row = 0; 
int col = 0; 
while (A[row][col] != -1) 
{ 
for (row = 0; row < A.length; row++) 
{ 
    for (col = 0; col < A[row].length; col++) 
     A[row][col] = scan.nextInt(); 
     } 
} 
+0

。你在做什么? '将每个数字分配给2d数组中的一个不同的单元格'是有点模糊的。 –

+0

我试图用扫描仪从一个文件中读取几个值,并将每个数字插入一个单元格,直到读取-1,while循环应该停止填充表格。 – Jim

回答

3

扫描需要发生在最内层循环中。此时,您可能需要重新阅读正在撰写的章节,并在发布到SO之前再花些时间研究问题。

... 

for (int col = 0; col < A[row].length; col++){ 
    A[row][col] = temp; 
    temp = scan.nextInt(); 
} 
... 

您可能还会发现,打印输出值在观看程序执行时非常有用。在temp中阅读的地方之后加上System.out.println(temp)。这会使问题变得明显。你也想改变你的while循环构造。截至目前,这没有多大意义。

+0

嘿,我试过你之前说过的话,但是当我这样做时,我得到一个noSuchElementException。我继续尝试修复while循环,但没有做任何事情。你可以看到上面编辑的代码。谢谢您的帮助。 – Jim

1

根据你的意见...这应该做你在问什么。你遇到的问题是,如果没有外部条件的某种条件,你无法摆脱内部循环。

请注意,我将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; 
     } 
    } 
} 
+0

请了解'if(...)'后面应该总是跟{...}'。 'else'也是一样。这只是帮助。无论如何+1为您的答案:) – dantuch

+0

@dantuch - 我了解有人在添加附加代码时遇到并搞砸条件的风险。这是说...有时我只是不觉得喜欢它)公平点的时候,显示一个新的程序员如何做一些事情,我会编辑。 (尽管我可以争辩说人们在添加代码时应该注意这些事情,因为它是一个有效的构造......) –