繁体   English   中英

for 循环只执行一次

[英]for loop only executes once

这是我的代码。 我的外循环只迭代一次而不是十次。 我知道这是因为System.out.println(i + " " + word)只发生一次。 我不理解为什么。

编辑:我已经添加了包含在其中的完整方法。创建字符数组的程序的一部分,用于制作单词搜索难题。 rows = 23. cols = 11. Word[] 是一个数组,它包括输入到数组中的每个单词的起始行和 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;
}

这是因为您使用了以下语法:

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

发生什么了:

  1. 您的代码中的某个地方抛出了异常StringIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException 异常会破坏您的for循环。
  2. catch块捕获异常,然后...
  3. 什么都不做,只是忽略 is 并继续。

所以,你应该至少添加这样的东西

e.printStackTrace()

在你的catch块。

永远不要忽略异常!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM