1

Today I restarted coding after a few months and tried do do Snake in the console. I tried to do it with a two-dimensional array and 2 for-loops.

public static void clearWindow() {
    String[][] board = new String[9][]; {
        for(int i=0; i<8; i++) {
            for(int o=0; 0<8; o++) {
                board[i][o]="O ";
                System.out.print(board[i][o]);
            }
            System.out.println("");
}}}

The Code has 2 mistakes which I can't find. The first one happens after 10 'O's are printed. It has something to do with board[i][o]="O ";

The second mistake is the System.out.println(""); . With this line, the code won't even run.

0

2 Answers 2

1

You have written 0 < 8 and not o < 8 in the condition of the inner loop. Zero will always be smaller than 8 that's why you end up in an endless loop and that's why your second Sysout will never get reached.

I would recommend using the well known names for running variables i for the outer loop and j for the inner one.

Sign up to request clarification or add additional context in comments.

Comments

0

Apart from the typo in the loop for(int o=0; 0<8; o++) there are other issues:

  1. 2D array board is not initialized properly which causes NullPointerException in line board[i][o]="O ";
  2. Unneeded statement block after initialization of board
  3. Actual dimensions of the board should be used in the loops.
  4. You seem to be creating a "clean" window, so you should return the board from this method. That being said, the code may be changed like this:
public static String[][] clearWindow() {
    String[][] board = new String[9][9];
    for(int i = 0; i < board.length; i++) {
        for(int j = 0; j < board[i].length; j++) {
            board[i][j]="O ";
            System.out.print(board[i][j]);
        }
        System.out.println();
    }
    return board;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.