我正在开发一个名为life的项目,该项目应该随机显示1为活着或0为死。当我执行程序时,零和一个继续打印。我查看了代码,我找不到错误。
public class Life {
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;i++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}
}
答案 0 :(得分:4)
以下main
方法
for (int j= 0 ; j < 5;i++)
您应该增加j
而不是i
。
答案 1 :(得分:2)
您的随机通话不在任何循环中。因此它是一个常数,它将使你保持循环。把随机调用放在循环中,你会没事的。
public static boolean firstgen(boolean[][] a)
{
int N = 5;
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
double cellmaker = Math.random();
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
正如Bhesh所指出的那样,在这里将i ++改为j ++
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b)== true)
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
答案 2 :(得分:2)
试试这些
//Makes the first batch of cells
public static boolean firstgen(boolean[][] a)
{
int N = 5;
double cellmaker = Math.random();
//boolean[][] b = new boolean[N][N];
for (int i = 0; i < N; i++)
{
for (int j= 0; j< N;j++)
{
if (cellmaker >0.5)
{
a[i][j]= true;
return true;
}
else
a[i][j]=false;
}
}
return false;
}
public static void main(String[] args)
{
boolean[][] b = new boolean[5][5];
//Placing the cells
for (int i =0;i < 5; i++)
{
for (int j= 0 ; j < 5;j++)
{
if (firstgen(b))
{
System.out.print("1"); //1 is live cell
}
else
System.out.print("0");// 0 is dead cell
}
System.out.println();
}
}