2011-09-18 78 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 - 我瞭解有人在添加附加代碼時遇到並搞砸條件的風險。這是說...有時我只是不覺得喜歡它)公平點的時候,顯示一個新的程序員如何做一些事情,我會編輯。 (儘管我可以爭辯說人們在添加代碼時應該注意這些事情,因爲它是一個有效的構造......) –