Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Multiple Variables in a FOR Loop

Tags:

People also ask

Can you initialize multiple variables in for loop?

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.

Can you initialize variables in a for loop?

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.

Can you initialize multiple variables at once?

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