2016-03-27 140 views
-2

這是我的代碼。我的外循環只迭代一次而不是十次。我知道這是因爲只發生一次。我不懂爲什麼。for循環僅執行一次

編輯:我已經添加了我的完整方法,這是包括在一個程序的一部分,以創建一個字符數組,使字搜索難題。行數= 23的cols = 11字[]是一個數組,其包括用於輸入到陣列中的每個字起始行和col值,如果該字將是水平或垂直等

public static char[][] createPuzzle(int rows, int cols, Word[] words) { 

    char[][] grid = new char[rows][cols]; 
    for (Word h : words) { 
     System.out.println(h.getWord()); 
    } 
    try{ 
     for(int i = 0; i<=9; i++){ 
      String word = words[i].getWord(); 
      System.out.println(i + " " + word); 
      boolean hor = words[i].isHorizontal(); 
      if (hor == true){ 
       for(int j = 0; j <= word.length(); j++){ 
        grid[words[i].getRow()][words[i].getCol()+j] = word.charAt(j); 
       } 
      } else if (hor == false){ 
       for(int k = 0; k <= word.length(); k++){ 
        grid[words[i].getCol()][words[i].getRow()+k] = word.charAt(k); 
       } 
      } 
     } 
    } catch (StringIndexOutOfBoundsException | ArrayIndexOutOfBoundsException e){ 
     //catches exception 
    } 
    return grid; 
} 
+0

爲什麼它只經過一次循環而不是10次 – redsoxfan

+0

據稱他的System.out.println(i +「」+ word);'只執行一次。 – Gendarme

+0

您是否收到任何錯誤和/或異常? –

回答

0

這是因爲您正在使用的語法如下:

} catch (StringIndexOutOfBoundsException | ArrayIndexOutOfBoundsException e){ 
     //catches exception 
} 

會發生什麼:

  1. Somethere在你的代碼中拋出的異常StringIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException。異常會破壞您的for循環。
  2. catch塊cathes例外,而且...
  3. 什麼,根本不理會是和那張。

所以,你應該在你的catch塊添加至少這樣的事情

e.printStackTrace() 

永遠不要忽略異常!