《炉石传说》随机卡组生成器card数组空指针异常求助
Hey there, let's break down why you're hitting that NullPointerException (NPE) in your Hearthstone deck generator and fix it up step by step!
The Root Cause of the NPE
First, let's zero in on the line throwing the error: card[a].setName(name);
You declared a static array static Card[] card = new Card[9999]; at the top of your class, but creating an array only allocates space for the container—each position in the array is still null by default. You're trying to call a method on a null Card object here, which triggers the NPE.
On top of that, there's a critical logic bug in your readFile() method: you're declaring int a = 0; inside the while(x.hasNext()) loop. That means every time the loop runs, a gets reset to 0—so you'd keep overwriting card[0] instead of filling the array sequentially.
Fixed readFile() Method
Here's the corrected version of the method that fixes both issues:
public static void readFile(){ int a = 0; // Move a outside the loop so it increments properly while(x.hasNext()){ // First, instantiate a new Card object for the current array position card[a] = new Card(); String name = x.next(); String character = x.next(); // Renamed to lowercase to follow Java conventions int health = Integer.parseInt(x.next()); int damage = Integer.parseInt(x.next()); int mana = Integer.parseInt(x.next()); int timesUsed = Integer.parseInt(x.next()); boolean hasTaunt = Boolean.parseBoolean(x.next()); boolean isMinion = Boolean.parseBoolean(x.next()); boolean isSpell = Boolean.parseBoolean(x.next()); card[a].setName(name); card[a].setCharacter(character); card[a].setHealth(health); card[a].setDamage(damage); card[a].setMana(mana); card[a].setTimesUsed(timesUsed); // Use the value read from the file instead of hardcoding 0 card[a].setHasTaunt(hasTaunt); card[a].setIsMinion(isMinion); card[a].setIsSpell(isSpell); a++; numberOfCards = a; // Update the count of loaded cards } closeFile(); }
Additional Tips to Avoid Future Issues
- Use
ArrayList<Card>instead of a fixed array: A fixed-length array (likeCard[9999]) is rigid—if you ever have more than 9999 cards, you'll hit an ArrayIndexOutOfBoundsException.ArrayList<Card>grows dynamically and is easier to work with. - Validate file input: Right now, if your
HearthCards.txthas a line with invalid data (e.g., a string where a number should be), you'll get aNumberFormatException. Add try-catch blocks or input checks to handle this gracefully. - Follow Java naming conventions: Variables like
Charactershould be lowercase (character) to make your code more readable for other developers.
内容的提问来源于stack exchange,提问作者Luke Moore

