Im trying to read deck.txt which is in the src directory of the application. The error I get is:
Exception in thread "main" java.lang.NullPointerException at Deck.(Deck.java:15) at TwentyOne.main(TwentyOne.java:7)
Line 7 in TwentyOne is just:
Deck deck = new Deck();
The file has a single integer on each line and is 104 lines long.
Where cards[i].suit.... is the line throwing the exception
try (BufferedReader br = new BufferedReader(new FileReader("src/deck.txt"))) {
for (int i = 0; i < 104; i++) {
cards[i].suit = Integer.parseInt(br.readLine());
cards[i].rank = Integer.parseInt(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
To try see what was wrong I copied this code out of eclipse into another directory with the file, this time just println(br.readLine()) rather than assigning it to the array and it worked fine.
Have I got the file in the wrong location or is there something else I'm missing? Thanks for your help
You are attempting to read 208 lines from your 104-line file. Each time you call br.readLine() the next line is read.
I'm assuming the format of the file is alternate lines for suit and rank, so try reducing the number of iterations to 52.
Edit: From the comments, the card array was declared but the card objects not initialised. Initialising the objects in the array before use fixed the NullPointerException.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments