Results 1 to 16 of 16
  1. #1
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default 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;
            }
               
    }








    Java 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 + ".");
        }
    }
    Moderator Edit: Code tags added to help post's readability
    Last edited by Fubarable; 03-17-2010 at 02:02 AM. Reason: Moderator Edit: Code tags added to help post's readability

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    What the heck???

  3. #3
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    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.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    This is not how you use a Scanner 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);
    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.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by bdario1 View Post
    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.
    the "What the Heck" was for all the garbage numbers that were in your first post. Your problem is noted above. Also, please look at my signature below to learn how to use code tags. Much luck!

  6. #6
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    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.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by bdario1 View Post
    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.
    Post your "fix."

    Also, what does the data file look like?

  8. #8
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    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

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    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?

  10. #10
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    Exception in thread "main" java.lang.NullPointerException
    at assignment07.GameWord.isValid(GameWord.java:113)
    at assignment07.NineteenGuessesGame1.main(NineteenGue ssesGame1.java:48)

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by bdario1 View Post
    Exception in thread "main" java.lang.NullPointerException
    at assignment07.GameWord.isValid(GameWord.java:113)
    at assignment07.NineteenGuessesGame1.main(NineteenGue ssesGame1.java:48)
    and which lines are those?

  12. #12
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    for GameWord line 113
    Java Code:
     
    			for(int i = 0; i < word.toString().length(); i ++)
    and for Nineteen line 48
    Java Code:
                   if(!fileWord.isValid())

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    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.

  14. #14
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    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?

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Follow the trail of the NPE as it will tell you where the problem is.

    Here
    Java Code:
    for (int i = 0; i < word.toString().length(); i++) {
    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.


    So then we trace back in the NPE to this line:
    Java Code:
    if (!fileWord.isValid()) {
    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:
          Scanner s = new Scanner(new File("five.txt")); 
          while (s.hasNext()) {
            wordCount++;
            GameWord fileWord = new GameWord(s);
    
            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"?

  16. #16
    bdario1 is offline Member
    Join Date
    Mar 2010
    Posts
    46
    Rep Power
    0

    Default

    Ok i see what you are saying but for some reason I am not seeing the fix. It seems like i need to add like you mentioned before something to the GameWord class under the (Scanner in) method, but i just don't know what?

Similar Threads

  1. Replies: 12
    Last Post: 01-04-2010, 03:53 PM
  2. NullPointer.exception in main (arrays)
    By Jana in forum New To Java
    Replies: 5
    Last Post: 02-20-2009, 06:41 PM
  3. nullpointer exception in jsp
    By fiero in forum JavaServer Pages (JSP) and JSTL
    Replies: 6
    Last Post: 11-07-2008, 01:44 PM
  4. Replies: 1
    Last Post: 03-08-2008, 06:41 PM
  5. NullPointer Exception
    By Preethi in forum New To Java
    Replies: 8
    Last Post: 02-06-2008, 03:40 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •