问题
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
回答1:
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.
回答2:
i in fact has not been initialized. for(int i=0, j=0;.... ); will do the trick for you.
回答3:
for (int i = 0, j = 0; ..........
回答4:
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++) {
}
来源:https://stackoverflow.com/questions/14533871/initializing-multiple-variables-in-a-for-loop