17

I'm a student trying to figure out how to fix a seemingly simple problem. I keep getting an error while trying to initialize 2 variables in a FOR loop. I'm trying to create rows for a game board. Why am I getting this error?

This is the method:

public String [] board;

public void printBoard(){
            for(int i, j = 0; i < this.board.length; i++, j++)
                if(j > 10)
                    System.out.println();
                else
                    System.out.print(this.board[i]);

> java:39: error: variable i might not have been initialized
2
  • Judging by the code, you probably also need to split the loop, to have a nested loop, in order to reach all game board pieces. As is, you will only hit the diagonals. Commented Jan 26, 2013 at 4:38
  • In java everything is very well documented before doing for loop just see basic syntax , and still if by mistake there is any error if you paste it to google it would diffidently be a better option , still if you dont find solution the post here Commented Jan 26, 2013 at 4:40

3 Answers 3

25

It's because you didn't initialized variable i, maybe zero or else.

for(int i = 0, j = 0; i < this.board.length; i++, j++)
            if(j > 10)
                System.out.println();
            else
                System.out.print(this.board[i]);

Don't forget to initialize a variable If some objects are using it.

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

Comments

4

i in fact has not been initialized. for(int i=0, j=0;.... ); will do the trick for you.

Comments

-1

This is Syntax. I think this will help you to initialize more than one variable for(int k = 0, dcount = 1; k < count; k++, dcount++) {

}

1 Comment

Well this topic is 4 yo, and the answer have been found since. Then I don't think your answer is necessary since it does not add anything to the other answers.

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.