如何以及在哪里添加要运行的主要方法?

时间:2013-09-09 15:41:21

标签: java main

所以我感觉好像代码已经完成并准备好运行,但是我遇到了基础知识的麻烦,完全忘记了把主要方法放在哪里以及放入什么内容。 我的班级被称为“细胞”,并且有一些方法等,现在我想运行它,对不起,如果我没有提供足够的细节,希望你们都会理解。 代码:

public class Cell {
//We need an array for the cells and one for the rules.

  public int[] cells = new int[9];

  public int[] ruleset = {0,1,0,1,1,0,1,0};







  //Compute the next generation.

public void generate() 
{

//All cells start with state 0, except the center cell has state 1.

    for (int i = 0; i < cells.length; i++)
    {
      cells[i] = 0;
    }

    cells[cells.length/2] = 1;


    int[] nextgen = new int[cells.length];
    for (int i = 1; i < cells.length-1; i++)
    {
      int left   = cells[i-1];
      int me     = cells[i];
      int right  = cells[i+1];
      nextgen[i] = rules(left, me, right);
    }
    cells = nextgen;

}

//Look up a new state from the ruleset.

  public int rules (int a, int b, int c)

  {
      if      (a == 1 && b == 1 && c == 1) return ruleset[0];

        else if (a == 1 && b == 1 && c == 0) return ruleset[1];

        else if (a == 1 && b == 0 && c == 1) return ruleset[2];

        else if (a == 1 && b == 0 && c == 0) return ruleset[3];

        else if (a == 0 && b == 1 && c == 1) return ruleset[4];

        else if (a == 0 && b == 1 && c == 0) return ruleset[5];

        else if (a == 0 && b == 0 && c == 1) return ruleset[6];

        else if (a == 0 && b == 0 && c == 0) return ruleset[7];


        return 0;
  }{


}
}

2 个答案:

答案 0 :(得分:1)

非常简单

public static void main(String[] args)
{
Cell cell = new Cell();
cell.generate();
}

在你的Cell类本身中添加它

答案 1 :(得分:1)

您可以在类声明中的任何位置编写主要方法

//this is your class declaration for class Cell!
public class Cell {

  //We need an array for the cells and one for the rules.
  public int[] cells = new int[9];
  public int[] ruleset = {0,1,0,1,1,0,1,0};


  //You can write main method here!


  //Compute the next generation.
  public void generate() 
  {
    //code
  }


  //Or you can write main method here!


  //Look up a new state from the ruleset.
  public int rules (int a, int b, int c)
  {
    //code
  }


  //Or, heck, you can write main method here:
  public static void main(String args[])
  {
    //sample code:
    Cell cell = new Cell();
    cell.generate();

    //loop through updated array list.
    for(int i = 0; i<cell.cells.length; i++)
    {
        System.out.println("cells[" + i + "]:  " + cell.cells[i]);
    }

    System.out.println("main method complete!");

  }


}

您还可以创建一个完整的其他类并在其中创建一个main方法来使用您编写的Cell类。

注意:在我修复的代码末尾附近有一个括号错误。