谁能解释一下它实际上是如何工作的?我仔细检查了我的笔记中的每一个步骤并全部写下来,它确实工作得很好,但为什么点总是 4?当我用 0 初始化它时,它对我来说没有意义......
Random rand = new Random();
int[][] map = new int[row][column];
int spot = 0;
int i=0;
int j=0;
/*ignore this part
for(i = 0; i<map.length; i++){
for(j = 0; j<map[i].length; j++) {
map[i][j] = rand.nextInt(2);
}
System.out.println();
}*/
System.out.println();
for(i =0; i<map.length; i++){
for(j =0; j<map[i].length; j++){
if(map[i][j] == 1){
while(spot<4){
map[i][j] = 5;
spot++;
}
}
System.out.print(map[i][j]+" ");
}
System.out.print(spot);
System.out.println();
}
System.out.println();
}
最佳答案
这一行:
System.out.print(spot);
您的数组只有 4 个成员,但在每行末尾打印“spot”的值时,您会在每行末尾打印 4 个成员。
编辑:仅在找到 1 时回复您关于增加“点”的评论:
if(map[i][j] == 1){
while(spot<4){ // <<<< you increase spot until it equals 4
map[i][j] = 5;
spot++;
}
}
如果您的目的是计算“1”出现的次数,则需要删除嵌套的 while
:
if(map[i][j] == 1){
map[i][j] = 5;
spot++;
}
关于java - 询问嵌套 for 循环内的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747914/