作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用 Java 创建康威的生命游戏,但似乎遇到了障碍。我创建了一个名为“Cell”的类,它包含一个 boolean 变量,该变量本质上确定细胞是活的还是死的,以及在需要时杀死或创建细胞的方法。在我的主要方法中,我获取用户在游戏中想要的行数和列数,并尝试创建一个 Cell 对象数组,每个对象都命名为“位置”。当我尝试运行代码并打印每个单元格的初始值时,我收到空指针异常错误,并且不确定如何修复它。据我所知,每个数组不应该有空值,但是我对此很陌生......
//Create a Cell class for the purpose of creating Cell objects.
公共(public)类 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//
}
这是我的 Cell 类(class)。如果一个单元格还活着,就会在它的位置打印一个单元格。如果死亡,则 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//
}
}
最佳答案
//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(); // location[i][j] not instantiated
}
System.out.print("\n");
}
在上面的 for 循环中: - 您尚未在数组中实例化 Cell 对象:-
location[i][j].printCell();
在此代码之前您需要执行以下操作:-
location[i][j] = new Cell();
关于Java新手: How to solve a NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923645/
我是一名优秀的程序员,十分优秀!