In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With