Results 1 to 5 of 5
Like Tree1Likes
  • 1 Post By JosAH

Thread: Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program:

  1. #1
    Selvart is offline Member
    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0

    Default Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program:

    Here is my code:
    Java Code:
    /**
     * Project #: 2
     *
     * Purpose of Program : The user will play an
     * entertaining (hopefully) game of hangman.
     *
     * Start Date: Nov 19, 2012
     *
     * End Date:
     *
    **/
    import java.io.*;
    
    public class twoHangman {
    
        BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));
    
        char alphabet;
        int life = 7;
        boolean instructions;
        char reply;
        boolean letterUsed;
        boolean wordIsRight;
    
    	String[] words = new String[20];
    
    	int choice = (int)(Math.random()*20);
    	char[] currentWord = words[choice].toCharArray();
    
    	int MAX_LENGTH = 26;
    	char[] used = new char [MAX_LENGTH];
    	       	char dataSize = 0;
    
    	char[] checkLetter = new char [5];
    
        public static void main(String[] args) throws IOException{
            new twoHangman();
        } //End of Main Method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        	//Constructor Method
        	twoHangman() throws IOException
        	{
    			words[0] = "gypsy";
    			words[1] = "agony";
    			words[2] = "ample";
    			words[3] = "cloak";
    			words[4] = "carol";
    			words[5] = "amber";
    			words[6] = "nymph";
    			words[7] = "depth";
    			words[8] = "month";
    			words[9] = "crypt";
    			words[10] = "brain";
    			words[11] = "debug";
    			words[12] = "dough";
    			words[13] = "shine";
    			words[14] = "dwarf";
    			words[15] = "foamy";
    			words[16] = "black";
    			words[17] = "crwth";
    			words[18] = "abyss";
    			words[19] = "glyph";
    
    			checkLetter[0] = '_';
    			checkLetter[1] = '_';
    			checkLetter[2] = '_';
    			checkLetter[3] = '_';
    			checkLetter[4] = '_';
    
    			welcomeScreen();
    			clearScreen();
    			menu();
        	} //End of Constructor method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
             //clearScreen method
            private void clearScreen() throws IOException
            {
                  centre("Press the enter key to continue ");
                    kb.readLine();
                  System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }    //End of clearScreen method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
            //exit method:
            private void exit() throws IOException
            {
                System.exit(0);
            } //End of exit method.
    
    //------------------------------------------------------------------------------------------------------------------------------
    
            //centring code System.out.println
            public void centreln(String s)
            {
                for(int count=0; count<(97-s.length())/2; count++)
                    {
                        System.out.print(" ");
                    } //End of For Loop
              System.out.println(s);
            } //End of System.out.println method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
            //centreing code centre
            public void centre(String s)
            {
                    for(int count=0; count<(97-s.length())/2; count++)
                    {
                        System.out.print(" ");
                    } //End of For Loop
                    System.out.print(s);
            }  //End of centre method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
    		//welcome screen method:
    		private void welcomeScreen()
    		{
    		   	System.out.println("");
        		System.out.println("");
            	System.out.println("'##::::'##::::'###::::'##::: ##::'######:::'##::::'##::::'###::::'##::: ##:");
        		System.out.println(" ##:::: ##:::'## ##::: ###:: ##:'##... ##:: ###::'###:::'## ##::: ###:: ##:");
        		System.out.println(" ##:::: ##::'##:. ##:: ####: ##: ##:::..::: ####'####::'##:. ##:: ####: ##:");
        		System.out.println(" #########:'##:::. ##: ## ## ##: ##::'####: ## ### ##:'##:::. ##: ## ## ##:");
        		System.out.println(" ##.... ##: #########: ##. ####: ##::: ##:: ##. #: ##: #########: ##. ####:");
            	System.out.println(" ##:::: ##: ##.... ##: ##:. ###: ##::: ##:: ##:.:: ##: ##.... ##: ##:. ###:");
       		 	System.out.println(" ##:::: ##: ##:::: ##: ##::. ##:. ######::: ##:::: ##: ##:::: ##: ##::. ##:");
          		System.out.println("..:::::..::..:::::..::..::::..:::......::::..:::::..::..:::::..::..::::..::");
        		System.out.println("");
        		System.out.println("						           |/|");
        		System.out.println("						           |/|");
        		System.out.println("						           |/|");
        		System.out.println("						           |/| /)");
        		System.out.println("						           |/|/\\/");
        		System.out.println("						           |/|\\/");
        		System.out.println("						          ()");
        		System.out.println("						          ()");
        		System.out.println("						          ()");
        		System.out.println("						          //\\");
        		System.out.println("						         / ,^./\\");
        		System.out.println("						        / /   \\/\\");
        		System.out.println("						       / /     \\/\\");
        		System.out.println("						      ( (       )/)");
        		System.out.println("						      | |       |/|");
        		System.out.println("						      | |       |/|");
        		System.out.println("						      | |       |/|");
        		System.out.println("						      ( (       )/)");
        		System.out.println("						       \\ \\     / /");
        		System.out.println("						        \\ `---' /");
        		System.out.println("						         `-----'");
            	System.out.println("");
            }//End of welcome screen method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        	//menu method
        	private void menu() throws IOException
            	{
    				char c;
    				do
    				// loop to make sure that the user enters a valid value
    				{
    					System.out.println("WHAT DO YOU WANT TO DO?");
    					System.out.println("I) Instructions");
    					System.out.println("S) Start Game");
    					System.out.println("X) Exit");
    					System.out.println("Enter your choice: ");
    					c = kb.readLine().charAt(0);
    					switch(c)
    					//switch statement for the values of choice
        					{
        						case 'i':
        						case 'I':
        						//if user enters 'i', the program does the following
        								instructions();
        								break;
        						case 's':
        						case 'S':
        						//if user enters 's', the program does the following
        								guess(alphabet, life, used, checkLetter);
        								break;
        						case 'x':
        						case 'X':
        						//if user enters 'x', the program does the following
        								exit();
        								break;
        						default:
        								System.out.println("INVALID CHOICE.");
    						}
        			} while (c != 's' && c != 'S' && c != 'x' && c != 'X');
    			} //End of menu method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
            //instructions method
        	private void instructions() throws IOException
            {
               	instructions = true;
               	//do while loop to make this run as long as instructions = true;
               	do
                {
                	do
                    {
    
    
                    	System.out.println("  ___         _               _   _             ");
                        System.out.println(" |_ _|_ _  __| |_ _ _ _  _ __| |_(_)___ _ _  ___");
                        System.out.println("  | || ' \\(_-<  _| '_| || / _|  _| / _ \\ ' \\(_-<");
                        System.out.println(" |___|_||_/__/\\__|_|  \\_,_\\__|\\__|_\\___/_||_/__/");
                        System.out.println("You will be prompted to guess a letter in a five letter word.");
                        System.out.println("You cannot guess the same word twice, if you do,");
                        System.out.println("you will be asked to guess again.");
                        System.out.println("You have 7 tries of guessing letters not guessed before.");
                        System.out.println("You win when you guess in 7 or under guesses. Have fun!");
                        centre("Do you understand these instructions? Enter y or n:");
                            reply = kb.readLine().charAt(0);
                         System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
                           if (reply != 'Y' && reply != 'y' && reply != 'N' && reply != 'n') {
                            System.out.println("You did not enter a value, please enter a valid value. \n");
                        }
                    } while (reply != 'Y' && reply != 'y' && reply != 'N' && reply != 'n');
    
                    	//switch statement for the values of reply
                    	switch (reply)
                    		{
                     			case 'Y':
                       			case 'y':
                       			//if user enters 'y', the program does the following
                            			System.out.println("Great! Let's start! ");
                            			instructions = false;
                            			break;
                        		case 'n':
                        		case 'N':
                        		//if user enters 'n', the program does the following
                                    System.out.println("  ___         _               _   _             ");
                                    System.out.println(" |_ _|_ _  __| |_ _ _ _  _ __| |_(_)___ _ _  ___");
                                    System.out.println("  | || ' \\(_-<  _| '_| || / _|  _| / _ \\ ' \\(_-<");
                                    System.out.println(" |___|_||_/__/\\__|_|  \\_,_\\__|\\__|_\\___/_||_/__/");
                                    System.out.println("You will be prompted to guess a letter in a five letter word.");
                                    System.out.println("You cannot guess the same word twice, if you do,");
                                    System.out.println("you will be asked to guess again.");
                                    System.out.println("You have 7 tries of guessing letters not guessed before.");
                                    System.out.println("You win when you guess in 7 or under guesses. Have fun!");
                               			instructions = false;
                            			break;
                        		default:
                            			System.out.println("Invalid choice. Type 'y' for yes and 'n' for no. ");
                    		}
                		} while (instructions == true);
                } //End of instructions method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        	//play method
            private void play() throws IOException
        	{
                do {
    					usedLetters(used, alphabet);
    
    					if (letterUsed = true)
    					{
    						System.out.println("You have already guessed this " + alphabet + " and the others listed above.");
        					guess(alphabet, life, used, checkLetter);
        					break;
    					}
    					else
        				{
        					life--;
        					underWord(currentWord , checkLetter, used);
        				} //only if the letter was not used, it will be checked for in the current word trying to be solved
    
    					checkWord(currentWord , checkLetter);
    
        				if (wordIsRight = true)
        				{
        					checkWordLife(currentWord , checkLetter);
        				}
    
        				if (life == 0)
        				{
        					checkWordLife(currentWord , checkLetter);
        				}
               	 } while (wordIsRight == false);
    
        	}//End of play method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
    	//underWord method to return the word with all characters not in letters replaced by _'s
    	private void underWord(char currentWord[] , char checkLetter[], char used[]) throws IOException
    	{
    		for (int index = 0; index<used.length; index++){
    			for (int i = 0; i<currentWord.length; i++) {
               		for (int n = 0; n<checkLetter.length; n++){
               			if ((used[index] == currentWord[i]) || (currentWord[i] == checkLetter[n]))
    					{
    						checkLetter[n] = currentWord[i];
    					}
           	   		}
    			}
            }
    
        }//End of underWord method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        //guess method to ask for user's guess
        private void guess(char alphabet, int life, char used[], char checkLetter[]) throws IOException
        {
        	centreln("You are trying to guess:");
    
    		for (int i = 0; i < checkLetter.length; i++)
            {
            	System.out.println(checkLetter[i]);
            }
    
    		centreln("You have guessed so far:");
    
    		for (int index = 0; index < used.length; index++)
    		{
                System.out.println(used[index]);
    		}
    
    		centreln("Guesses left: " + life);
    
        	System.out.println("Guess a letter in this 5-letter word: ");
        	alphabet = kb.readLine().charAt(0);
        	play();
        }//End of guess method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        //usedLetters method to check if user's guess has already been guessed
        private boolean usedLetters(char used[], char alphabet) throws IOException
    	{
    		boolean letterUsed = true;
    		for(int x=0; x<used.length; x++)
    		{
    			if(alphabet == used[x])
    			{
    				letterUsed = true;
    			}
    			else
    			{
    				letterUsed = false;
    			}
    		}
    		used[dataSize] = alphabet;
    		return letterUsed;
    	}//End of usedLetters method
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        //checkWord method to see if the user has got the correct word
        private boolean checkWord(char currentWord[], char checkLetter[]) throws IOException
        {
            boolean wordIsRight = true;
            for(int x=0; x<currentWord.length; x++)
            {
               	if(checkLetter == currentWord)
                {
                	wordIsRight = true;
                }
                else
    			{
    				wordIsRight = false;
    			}
            }
            return wordIsRight;
        }//End of checkWord method
    
    
    //------------------------------------------------------------------------------------------------------------------------------
    
        //checkWordLife method to see if the user has got the correct word after they have run out of lives
        private void checkWordLife(char currentWord[], char checkLetter[]) throws IOException
        {
            for(int x=0; x<currentWord.length; x++)
            {
               	if(checkLetter == currentWord)
                {
                	System.out.println("HUZZAH! You have guessed the word!");
                	System.out.println("You have completed this game of hangman.");
                	menu();
                }
    
                {
                    System.out.println("You have run out of guesses!");
                    System.out.println("The word was:");
                    	for (int index = 0; index < currentWord.length; index++)
                    	{
                    		System.out.print(currentWord[index]);
                    	}
    				menu();
            	}
        	}
        }//End of checkWordLife method
    }
    
    //------------------------------------------------------------------------------------------------------------------------------
    I get this when I try to run:

    Exception in thread "main" java.lang.NullPointerException?
    at twoHangman.<int><twoHangman.java:30>
    at twoHangman.main<twoHangman.java:39>

    I am not experienced and I am not familiar with Java. I cannot detect any mistakes...Any help will be appreciated!
    Last edited by JosAH; 12-21-2012 at 06:57 PM.

  2. #2
    Sierra is offline AN21XX
    Join Date
    Mar 2012
    Location
    Munich
    Posts
    297
    Rep Power
    3

    Default Re: Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program

    Woah... please tag your code with the forum code brackets and indent it correctly, it is unreadable like that...
    I try guessing as long:
    char[] currentWord = words[choice].toCharArray();

    Are you sure you have a valid string in 'words[choice]' here?
    I like likes!

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default Re: Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program

    I added those code tags, just because I was so curious about the ASCII art ...

    kind regards,

    Jos

    ps. it is too much code though ...
    Sierra likes this.
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default Re: Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program

    Some of the code should be moved inside the constructor so it executes after the other variables have been initialized.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: Error: Exception in thread "main" java.lang.NullPointerException? Hangman Program

    Yes, there is code outside of the constructor that uses the words array to set the currentWord, but this is done before the words array is initialized, so all of the words in the array are all null. That's why you're getting the NullPointerException.

    All of the changes to your code are near the top, so I won't give you your whole listing back just the part that I changed for you.

    I noticed that after these changes, hangman runs, but the guess() method will still need some work to keep track of right and wrong guesses.

    But here's the part of the code that fixes the NullPointerException:

    Java Code:
    /**
     * Project #: 2
     *
     * Purpose of Program : The user will play an
     * entertaining (hopefully) game of hangman.
     *
     * Start Date: Nov 19, 2012
     *
     * End Date:
     *
     **/
    import java.io.*;
    
    public class twoHangman {
    
    	BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));
    
    	char alphabet;
    	int life = 7;
    	boolean instructions;
    	char reply;
    	boolean letterUsed;
    	boolean wordIsRight;
    
    	String[] words = new String[20];
    
    	char[] currentWord; // <<<<< declare currentWord here so it's available throughout the class, but don't init it until we're in the constructor after the word array initialized
    
    	int MAX_LENGTH = 26;
    	char[] used = new char [MAX_LENGTH];
    	char dataSize = 0;
    
    	char[] checkLetter = new char [5];
    
    	public static void main(String[] args) throws IOException{
    		new twoHangman();
    	} //End of Main Method
    
    	//------------------------------------------------------------------------------------------------------------------------------
    
    	//Constructor Method
    	twoHangman() throws IOException
    	{
    		words[0] = "gypsy";
    		words[1] = "agony";
    		words[2] = "ample";
    		words[3] = "cloak";
    		words[4] = "carol";
    		words[5] = "amber";
    		words[6] = "nymph";
    		words[7] = "depth";
    		words[8] = "month";
    		words[9] = "crypt";
    		words[10] = "brain";
    		words[11] = "debug";
    		words[12] = "dough";
    		words[13] = "shine";
    		words[14] = "dwarf";
    		words[15] = "foamy";
    		words[16] = "black";
    		words[17] = "crwth";
    		words[18] = "abyss";
    		words[19] = "glyph";
    		
    		// ***** don't initialize currentWord until after the words array is initialized ****
    		int choice = (int)(Math.random()*20);
    		currentWord = words[choice].toCharArray();
    
    		checkLetter[0] = '_';
    		checkLetter[1] = '_';
    		checkLetter[2] = '_';
    		checkLetter[3] = '_';
    		checkLetter[4] = '_';
    
    		welcomeScreen();
    		clearScreen();
    		menu();
    	} //End of Constructor method
    
    .... I didn't change the code after this point

Similar Threads

  1. Replies: 5
    Last Post: 12-21-2011, 06:44 PM
  2. Replies: 10
    Last Post: 07-20-2011, 02:11 PM
  3. Replies: 5
    Last Post: 06-22-2010, 03:51 PM
  4. Replies: 6
    Last Post: 07-16-2009, 03:30 PM
  5. Replies: 1
    Last Post: 07-16-2009, 10:35 AM

Tags for this Thread

Posting Permissions

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