1

我正在从事一个名为 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();
  }
}

}

4

3 回答 3

4

在以下您的main方法中

for (int j= 0 ; j < 5;i++)

你应该增加j而不是i.

于 2012-11-14T01:01:36.570 回答
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 
     }
于 2012-11-14T01:02:14.890 回答
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();
    }
}
于 2012-11-14T01:22:13.900 回答