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

    Default Help with methods usage

    I have two classes one called GameWord and the other NineteenGame which should be the the methods created in GameWord for the NineteenGame class to be used.

    Here is the original NineteenGame class this is what once i am done with my GameWord class this is how it should run.
    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 NineteenGuessesGame2
    {
        /**
         * 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.
    	
            String correctWord = "";
            
            try
            {
                int wordCount = 0;
                Scanner s = new Scanner (new File ("five.txt"));
                while (s.hasNext())
                {
                    wordCount++;
                    String word = s.next();
                    
                    boolean wordIsValid = true;
                    
                    for (int i = 0; i < word.length(); i++)
                        if (!Character.isLowerCase(word.charAt(i)))
                                wordIsValid = false;
                    
                    if (word.length() != 5)
                        wordIsValid = false;
                    
                    if (!wordIsValid)
                    {
                        System.out.println ("The file five.txt contains invalid words.  Example: " + word);
                        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 = s.next();
            }
            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 ++;
                
                String userGuess = "";
                boolean okGuess = false;
                
                while (!okGuess)
                {                
                    System.out.print ("Enter guess # " + guessNumber + ": ");
                    userGuess = input.next().toLowerCase();
                    okGuess = true;
                    
                    for (int i = 0; i < userGuess.length(); i++)
                        if (!Character.isLowerCase(userGuess.charAt(i)))
                            okGuess = false;
                    
                    if (userGuess.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)
                {
                    String a = correctWord;
                    String b = userGuess;
                    
                    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++;
                    }
                    
                    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 + ".");
        }
    }
    Here is mine GameWord class
    Java Code:
    package assignment07;
    import java.io.File;
    import java.io.FileNotFoundException;
    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)
    	{	
    	 this.word = in.next().toLowerCase();
    		//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 = this.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 = this.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;
    		}
    			
    }
    and here is mine NineteenGame class that i am using the methods i created from the GameWord class.
    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);
           // String wordone = input.nextLine();
            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();
                                    
                    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 + ".");
        }
    }
    and when i run mine it does not work correctly once i type only 3 or 4 or 6 characters it is an infinite loop and also it does not print the Enter guess #.
    This is what it should do
    Welcome to the Nineteen Guesses Game.
    -------------------------------------

    You have nineteen guesses to guess which five-letter word I have selected.
    After each guess I will tell you how similar your word is to my word.

    Enter guess # 1:


    and mine does this
    Welcome to the Nineteen Guesses Game.
    -------------------------------------

    You have nineteen guesses to guess which five-letter word I have selected.
    After each guess I will tell you how similar your word is to my word.

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    can you be specific, i mean did you find what the loop cause for this.

    You can debug the code in many ways. If you are working on an IDE then put some breakpoints where you want to capture user information. Or else if you are working on with the console then put some print statement and check parameter values.

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. SerialModemGateway() Usage
    By ajaxjagadish in forum Advanced Java
    Replies: 1
    Last Post: 03-25-2010, 08:24 AM
  3. usage of Hashtable
    By venu2807 in forum New To Java
    Replies: 4
    Last Post: 01-27-2009, 03:36 AM
  4. Need help with AST usage on Eclipse! Thanks!
    By j_aquino314 in forum Eclipse
    Replies: 0
    Last Post: 10-08-2008, 07:15 PM
  5. Comm API Usage
    By hobbyist in forum New To Java
    Replies: 0
    Last Post: 11-16-2007, 04:59 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
  •