I am having some problems in getting a loop to work. My goal is to create a loop which will allow the user to fill in lottery numbers in several rows (the user may decide how many rows he/she wants to fill out, but it can not be more than a maximum number specified earlier in the code). So far, my code 开发者_StackOverflow社区is as follows:
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;
}
When I try to run this in a main-method, and I enter a proper number of rows, I get the error message:
Exception in thread "main" java.lang.NullPointerException at LotteryTicket.fillInTicket(LotteryTicket.java:24)
Line 24 is the line in which I call upon the fillInRow()-method which I have created in another class, so I suspect the problem lies here. I know that this method works fine, as I have tried it in a test program. However, am I not referring correctly to this fillInRow()-method?
Any help will be much appreciated!
You created an array with size maxNumberOfRows
, but you haven't populated it with any objects. It initially just contains null references.
To fix the code, you have to call the LotteryRow
constructor to create an object and then put a reference to that object in your array. You can fix your code like this:
for (int index = 0; index < n; index++) {
rows[index] = new LotteryRow();
rows[index].fillInRow();
}
You must create a new object and place it in the array before you call a method on it. Java arrays of objects are initialized to all nulls.
You never initialize rows
. Yes, you create the Array with this.rows = new LotteryRow[maxNumberOfRows];
but that does NOT create a new LotteryRow Object for every Array Entry, so the whole array is filled with null
. You have to create the LotteryRow Objects by yourself
精彩评论