2016-03-27 293 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() 

永远不要忽略异常!