gpt4 book ai didi

java - 循环/数组(Java)

转载 作者:行者123 更新时间:2023-12-04 06:11:42 24 4
gpt4 key购买 nike

我在使循环工作时遇到了一些问题。我的目标是创建一个循环,允许用户在几行中填写彩票号码(用户可以决定他/她想要填写多少行,但不能超过前面指定的最大数量)代码)。到目前为止,我的代码如下:

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”中的异常 java.lang.NullPointerException
在 LotteryTicket.fillInTicket(LotteryTicket.java:24)

第 24 行是我调用在另一个类中创建的 fillInRow() 方法的行,所以我怀疑问题出在这里。我知道这种方法效果很好,因为我已经在测试程序中尝试过。但是,我是不是正确地提到了这个 fillInRow() 方法?

任何帮助都感激不尽!

最佳答案

您创建了一个大小为 maxNumberOfRows 的数组,但你没有用任何对象填充它。它最初只包含空引用。

要修复代码,您必须调用 LotteryRow构造函数来创建一个对象,然后将对该对象的引用放入您的数组中。你可以像这样修复你的代码:

for (int index = 0; index < n; index++) {
rows[index] = new LotteryRow();
rows[index].fillInRow();
}

关于java - 循环/数组(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com