我在运行循环时遇到了一些问题。我的目标是创建一个循环,允许用户在几行中填写彩票号码(用户可以决定他/她想要填写多少行,但它不能超过前面代码中指定的最大数量)。到目前为止,我的代码如下:
import java.util.Scanner;
public class LotteryTicket {
public LotteryRow[] rows;
public int numberOfRows;
public Player ticketOwner;
public LotteryTicket(int maxNumberOfRows) {
this.rows = new LotteryRow[maxNumberOfRows];
}
Scanner input = new Scanner(System.in);
public void fillInTicket() {
System.out.print("How many rows do you want to fill in? ");
int n = input.nextInt();
while (n < 1 || n > rows.length) {
System.out.println("The number of rows must lie between 1 and " + rows.length);
System.out.print("How many rows do you want to fill in? ");
n = input.nextInt();
}
for (int index = 0; index < n; index++) {
rows[index].fillInRow();
}
numberOfRows = n;
}当我尝试在main-method中运行它,并且输入了适当的行数时,我得到了错误消息:
LotteryTicket.fillInTicket(LotteryTicket.java:24)处的线程"main“java.lang.NullPointerException出现异常
第24行是我调用在另一个类中创建的fillInRow()-method的行,所以我怀疑问题出在这里。我知道这个方法工作得很好,因为我已经在测试程序中尝试过了。但是,我是不是正确地引用了这个fillInRow()-method?
任何帮助都将不胜感激!
发布于 2011-10-10 01:50:44
您创建了一个大小为maxNumberOfRows的数组,但是还没有用任何对象填充它。它最初只包含空引用。
要修复代码,您必须调用LotteryRow构造函数来创建一个对象,然后将对该对象的引用放入数组中。你可以像这样修复你的代码:
for (int index = 0; index < n; index++) {
rows[index] = new LotteryRow();
rows[index].fillInRow();
}发布于 2011-10-10 01:51:04
在调用新对象上的方法之前,必须先创建一个新对象并将其放入数组中。对象的Java数组被初始化为所有空值。
发布于 2011-10-10 01:54:19
您永远不会初始化rows。是的,您可以使用this.rows = new LotteryRow[maxNumberOfRows];创建数组,但这不会为每个数组条目创建一个新的LotteryRow对象,因此整个数组都填充了null。您必须自己创建LotteryRow对象
https://stackoverflow.com/questions/7705332
复制相似问题