简体   繁体   中英

for loop only executes once

Here is my code. My outer loop only iterates once instead of ten times. I know this because System.out.println(i + " " + word) only happens once. I do not understand why.

edit: I've added my full method that this is included in. Part of a program to create a character array that makes a word search puzzle. rows = 23. cols = 11. Word[] is an array that includes starting row and col value for each word entered into the array, if the word will be horizontal or vertical, etc.

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;
}

This is because you are using the following syntax:

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

What happens:

  1. Somethere in your code was thrown an exception StringIndexOutOfBoundsException or ArrayIndexOutOfBoundsException . The exception breaks your for loop.
  2. catch block cathes the exception, and...
  3. does nothing , just ignores is and goes on.

So, you should add at least something like this

e.printStackTrace()

at your catch block.

Never ignore exceptions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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