1

私は life と呼ばれるプロジェクトに取り組んでいます。このプロジェクトは、生きている場合は 1、死んでいる場合は 0 をランダムに表示することになっています。プログラムを実行すると、0 と 1 が出力され続けます。私はコードを調べましたが、間違っていることがわかりませんでした。

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 に答える