我正在尝试用 Java 创建 Conway 的生活游戏,但似乎遇到了障碍。我创建了一个名为“Cell”的类,它包含一个布尔变量,该变量基本上确定细胞是活的还是死的,以及在需要时杀死或创建细胞的方法。在我的主要方法中,我获取用户在他们的游戏中想要的行数和列数,并尝试创建一个 Cell 对象数组,每个对象都命名为“位置”。当我尝试运行代码并打印每个单元格的初始值时,我得到一个空指针异常错误并且不知道如何修复它。据我所知,每个数组都不应该有一个空值,但是我对此很陌生......
//Create a Cell class for the purpose of creating Cell objects.
public class Cell
{
private boolean cellState;
//Cell Constructor. Initializes every cell's state to dead.
public Cell()
{
cellState = false;
}
//This function kills a cell.
//Should be called using objectName[x][y].killCell.
public void killCell()
{
cellState = false;
}
//This function creates a cell.
//Should be called using objectName[x][y]createCell.
public void createCell()
{
cellState = true;
}
public void printCell()
{
if (cellState == true)
{
System.out.print("1");
}
else if
{
System.out.print("0");
}
}
//End Class Cell//
}
这是我的细胞课。如果一个单元格是活的,则会在其位置上打印一个单元格。如果死了,0 将代替它的位置。
这是我的主要方法。错误发生在我创建 Cell 对象数组的行。我做这一切都错了吗?
//GAME OF LIFE//
import java.util.Scanner;
import java.lang.*;
public class GameOfLife
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("\t\tWelcome to the Game of Life!");
System.out.println("\n\nDeveloped by Daniel Pikul");
System.out.print("\n\nHow many rows would you like your game to have?");
int numRows = scan.nextInt();
System.out.print("How many columns would you like your game to have?");
int numColumns = scan.nextInt();
//Create an array of cell objects.
Cell[][] location = new Cell[numColumns][numRows];
//This for loop will print out the cell array to the screen.//
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numColumns; j++)
{
location[i][j].printCell();
}
System.out.print("\n");
}
//Prompt the user to enter the coordinates of cells that should live.
System.out.println("Input coordinates tocreate active cells.");
int xCo, yCo;
char userChoice;
//This do loop takes coordinates from the user. Every valid coordinate
//creates a living cell in that location.
do
{
System.out.print("Enter an x coordinate and a y coordinate: ");
xCo = scan.nextInt();
yCo = scan.nextInt();
location[xCo][yCo].createCell();
System.out.print("Enter another coordinate? (Y/N) ");
String tempString = scan.next();
userChoice = tempString.charAt(0);
}while(userChoice == 'Y');
//THIS IS AS FAR AS I HAVE GOTTEN IN THE PROGRAM THUS FAR//
}
}