Results 1 to 16 of 16
Thread: NullPointer exception
- 03-17-2010, 01:52 AM #1
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
NullPointer exception
I have two .java files one called GameWord and other NinetenGame the nineteen game should call the classes from the GameWord that i create so it simplifies the code and i can't get it to work i keep getting the nullPointer exception here is the code i have so far. Please help i really need it. Thank You.
Java Code:package assignment07; import java.util.Scanner; /** * The GameWord objects represent words in the NineteenGuessesGame application. * The words are stored in the separate objects. The GameWord objects will be used to * represent the secret word and the users guess. * <p> * * Class contains methods that are validating GameWords. * * @author * @version * @ta * */ public class GameWord { /** * In this variable the word from the NineteenGuesses Game will be stored. * <p> * Abstracting - word: a String containing the word. * */ private String word; /** * It builds a GameWord object using a test word. * <p> * * This constructor will not be used in the NineteenGuessesGame * it will test the GameWord class with specific words. * <p> * * In case the word is empty or null it is replaced with one of strings: * "Invalid word: empty" * "Invalid word: null" * <p> * * This is helpful in a way that it will guarantee that the GameWord * objects meet the representation. * @param test A word used for testing the GameWord class. */ public GameWord(String test) { this.word = test; if(word == null) word = "Invalid word: null"; if(word.length()== 0) word = "Invalid word: empty"; } /** * This builds a GameWord object from the Scanner object. This allows * objects to be built from user input or from a file. * <p> * * This is where the Scanner is created that will gather words from either * keyboard or file input and will be used throughout the NineteenGuessesGame application. * It will also pass it to the constructor to read words and use them to build objects. * * <p> * In case the word is empty or null it is replaced with one of strings: * "Invalid word: empty" * "Invalid word: null" * * @param in Input source for the objects word */ public GameWord (Scanner in) { //Code added later } /** * It compares tow GameWord objects to see if they are the same word. They will * be equal only if all of the characters match exactly. * <p> * * @param otherWord The object to compare to 'this' * @return true if 'this' and 'other' are the same word */ public boolean equals (GameWord otherWord) { if(this.word.equals(otherWord.toString())) return true; else return false; } /** * Returns the String representation of the GameWord. * * @return the word, as a String */ public String toString() { return word; } /** * This will return true if this object is a five-letter lower case word. * <p> * * Otherwise false will be returned if: * Any character is not a lower case letter. * And the word is not five characters long. * * @return true if it word is valid and false otherwise */ public boolean isValid() { boolean wordIsValid = true; for(int i = 0; i < word.toString().length(); i ++) { if(!Character.isLowerCase(word.charAt(i))) wordIsValid = false; if(word.toString().length() != 5) wordIsValid = false; } return wordIsValid; } /** * This method is used to count and return the number of the correct characters * that match exactly between 'this' GameWord and some 'other' GameWord. In order for it * to match exactly characters must be in the same position. * <p> * * In case the 'this' or 'other' are not valid GameWord, the comparison is done and the * invalid result is returned if valid an integer between 0...5 will be returned. * * <p> * * @param other the word to compare to 'this' * @return number of exactly matching characters. */ public int countCorrect(GameWord other) { String a = word; String b = other.word; int correctLetters = 0; int misplacedLetters = 0; int index = 0; while (index < a.length()) { if (a.charAt(index) == b.charAt(index)) { correctLetters++; a = a.substring(0, index) + a.substring(index+1); b = b.substring(0, index) + b.substring(index+1); } else index++; } return correctLetters; } /** * In this method the number of characters that are identical but in different * position between 'this' GameWord and some 'other' GameWord. If the character is repeated * more than one time it is counted only once. Characters that match and are in same position * are not counted. * * <p> * * In case the 'this' or 'other' are not valid GameWord, the comparison is done and the * invalid result is returned if valid an integer between 0...5 will be returned. * <p> * * @param other the word to compare to 'this' * @return the number of matching characters that are misplaced. */ public int countMissplaced(GameWord other) { String a = word; String b = other.word; int correctLetters = 0; int misplacedLetters = 0; int index = 0; while (index < a.length()) { if (a.charAt(index) == b.charAt(index)) { correctLetters++; a = a.substring(0, index) + a.substring(index+1); b = b.substring(0, index) + b.substring(index+1); } else index++; } int aIndex = 0; while (aIndex < a.length()) { int bIndex = 0; while (aIndex < a.length() && bIndex < b.length()) { if (a.charAt(aIndex) == b.charAt(bIndex)) { misplacedLetters++; a = a.substring (0, aIndex) + a.substring(aIndex+1); b = b.substring (0, bIndex) + b.substring(bIndex+1); bIndex = 0; } else bIndex++; } aIndex++; } return misplacedLetters; } }
Moderator Edit: Code tags added to help post's readabilityJava Code:package assignment07; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * This applications plays a Mastermind-like game * using five-letter words. The user has nineteen * guesses to find a secret word. After each guess, * the game reports how many letters were exactly * right (and in the correct position), and how many * letters were right but in the wrong position. * <p> * * Possible words are read from a text file filled * only with five-letter words. * * @author * @version */ public class NineteenGuessesGame1 { /** * The Nineteen game application entry point. * <p> * * Note: Command line arguments are ignored. * * @param args command line arguments */ public static void main (String[] args) { // This code is intentionally uncommented. // It is part of the assignment to figure // out what this code is doing. GameWord correctWord = new GameWord(""); try { int wordCount = 0; Scanner s = new Scanner (new File ("five.txt")); while (s.hasNext()) { wordCount++; GameWord fileWord = new GameWord(s); if(!fileWord.isValid()) { System.out.println ("The file five.txt contains invalid words. Example: " + fileWord); s.close(); return; } } s.close(); int wordIndex = (int) (Math.random() * wordCount); s = new Scanner (new File ("five.txt")); for (int i = 0; i < wordIndex; i++) s.next(); correctWord = new GameWord(s); } catch (IOException e) { System.out.println ("Unable to read the file five.txt - program terminated."); return; } System.out.println ("Welcome to the Nineteen Guesses Game."); System.out.println ("-------------------------------------"); System.out.println(); System.out.println ("You have nineteen guesses to guess which five-letter word I have selected."); System.out.println ("After each guess I will tell you how similar your word is to my word."); System.out.println(); Scanner input = new Scanner(System.in); int guessNumber = 0; boolean playerGotIt = false; while (guessNumber < 19 && !playerGotIt) { guessNumber ++; GameWord userGuess = new GameWord(input); boolean okGuess = false; while (!okGuess) { System.out.print ("Enter guess # " + guessNumber + ": "); okGuess = userGuess.isValid(); for (int i = 0; i < userGuess.toString().length(); i++) if (!Character.isLowerCase(userGuess.toString().charAt(i))) okGuess = false; if (userGuess.toString().length() != 5) okGuess = false; if (!okGuess) { System.out.println ("Invalid entry - try again."); System.out.println(); } } if (userGuess.equals(correctWord)) playerGotIt = true; else if (guessNumber != 19) { int correctLetters = userGuess.countCorrect(correctWord); int misplacedLetters = userGuess.countMissplaced(correctWord); System.out.println ("Your guess is incorrect: " + userGuess); System.out.println (correctLetters + " of your letter(s) are correct and in the correct position."); System.out.println (misplacedLetters + " of your letter(s) are correct but misplaced."); System.out.println (""); } } if (playerGotIt) System.out.println ("Congratulations! You guessed the word in " + guessNumber + " guesses."); else System.out.println ("You have used up your nineteen guesses. The word was " + correctWord + "."); } }Last edited by Fubarable; 03-17-2010 at 02:02 AM. Reason: Moderator Edit: Code tags added to help post's readability
-
What the heck???
- 03-17-2010, 02:02 AM #3
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
I am having the problem of finding why it keeps pulling the null pointer exception cant seem to resolve it. They are two .java documents and the big gap is separating the first one from another.
-
This is not how you use a Scanner object:
Instead call nextLine() on the input Scanner object to get a guess from the user, and then use that String to create a new GameWorld object.Java Code:Scanner input = new Scanner(System.in); int guessNumber = 0; boolean playerGotIt = false; while (guessNumber < 19 && !playerGotIt) { guessNumber++; GameWord userGuess = new GameWord(input);
-
- 03-17-2010, 02:15 AM #6
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
Ok fixed that but still getting the same null pointer exception?? And for garbage i was not sure when i saw it i fixed it right away.
-
- 03-17-2010, 02:21 AM #8
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
Scanner input = new Scanner(System.in);
String wordone = input.nextLine();
int guessNumber = 0;
boolean playerGotIt = false;
while (guessNumber < 19 && !playerGotIt)
{
guessNumber ++;
GameWord userGuess = new GameWord(wordone);
The file looks like this just bunch of words that are 5 characters long.
addle
adios
baldy
bates
batik
beaux
bebop
bergs
bezel
bicep
blest
bogey
boggy
bongo
boson
bossy
briny
butch
cabal
cacao
caddy
cadet
cadre
cagey
cairn
cameo
canny
carps
catty
caulk
ceded
cedar
cello
champ
-
Again, please use code tags when posting code. Again, please read my signature to learn how to do this.
Next, are you sure that you're getting a NullPointerException (NPE) now? If so, which line is throwing this exception?
- 03-17-2010, 02:27 AM #10
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
Exception in thread "main" java.lang.NullPointerException
at assignment07.GameWord.isValid(GameWord.java:113)
at assignment07.NineteenGuessesGame1.main(NineteenGue ssesGame1.java:48)
-
- 03-17-2010, 02:41 AM #12
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
for GameWord line 113
and for Nineteen line 48Java Code:for(int i = 0; i < word.toString().length(); i ++)
Java Code:if(!fileWord.isValid())
-
You're initializing your GameWorld objects with a Scanner object, but if you look at the GameWorld code, this constructor doesn't appear to have been fleshed out:
Java Code:public GameWord(Scanner in) { // Code added later }
Unless you get an updated GameWorld class that will truly use a Scanner object, you probably should avoid using this constructor and instead use the other constructor that takes a String parameter.
HTH and much luck.
- 03-17-2010, 03:04 AM #14
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
I am still kind of lost i thought i was not using the scanner in the GameWord class instead the string one in Nineteen? Could you show me what you mean?
-
Follow the trail of the NPE as it will tell you where the problem is.
Here
if this line throws a NPE, it must be because word is null since it's the only object that is being dereferenced on this line. word is a field of the GameWorld class, and if not initialized is null.Java Code:for (int i = 0; i < word.toString().length(); i++) {
So then we trace back in the NPE to this line:
fileWorld is the GameWorld object that has the null word object. So then you look a few lines up in your code to where you initialize this object:Java Code:if (!fileWord.isValid()) {
and we see that fileWorld is initialized via new GameWorld(s). So then you check to see what type of object is "s"?Java Code:Scanner s = new Scanner(new File("five.txt")); while (s.hasNext()) { wordCount++; GameWord fileWord = new GameWord(s); if (!fileWord.isValid()) {
- 03-17-2010, 04:44 AM #16
Member
- Join Date
- Mar 2010
- Posts
- 46
- Rep Power
- 0
Similar Threads
-
Nullpointer exception, even tho I can print data from the file!
By Addez in forum New To JavaReplies: 12Last Post: 01-04-2010, 03:53 PM -
NullPointer.exception in main (arrays)
By Jana in forum New To JavaReplies: 5Last Post: 02-20-2009, 06:41 PM -
nullpointer exception in jsp
By fiero in forum JavaServer Pages (JSP) and JSTLReplies: 6Last Post: 11-07-2008, 01:44 PM -
Trouble with factory method - unhandled exception type Exception
By desmond5 in forum New To JavaReplies: 1Last Post: 03-08-2008, 06:41 PM -
NullPointer Exception
By Preethi in forum New To JavaReplies: 8Last Post: 02-06-2008, 03:40 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks