Initializing Multiple Variables in a FOR Loop

大兔子大兔子 提交于 2020-01-03 06:58:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!