所以我觉得代码已经完成并准备好运行,但我在基础知识方面遇到了问题,完全忘记了将主方法放在哪里以及在其中放什么。我的类叫做"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};
//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;
}{
}
}
非常简单
public static void main(String[] args)
{
Cell cell = new Cell();
cell.generate();
}
将其添加到 Cell 类本身中
您可以在类声明中的任何位置编写 main 方法:
//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 类。
注意:您在代码末尾附近有一个括号错误,我在这里修复了该错误。