pasha_codes
pasha_codes

Reputation: 635

Initializing Multiple Variables in a FOR Loop

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

Upvotes: 17

Views: 49587

Answers (3)

AMIT MISHRA
AMIT MISHRA

Reputation: 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++) {

}

Upvotes: -1

user948620
user948620

Reputation:

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.

Upvotes: 25

rtcarlson
rtcarlson

Reputation: 424

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

Upvotes: 4

Related Questions