AP CSP & Java : I/O & String Manipulation

"Success is the ability to go from one failure to another with no loss of enthusiasm." Winston Churchill

Demonstration for Create Task : Java Console Input/Output with String manipulation

 

import java.util.Scanner;

public class HangmanGame
{
	private static String  wordString;            // the word to be guessed as a String
	private static char[]  word;                  // the word to be guessed as an array of characters
	private static String  userInput;             // letter (or guess) typed in by user
	private static int     numGuesses     = 0;    // number of guesses attempted
	private static int     more           = 4;    // number of more (i.e. wrong) guesses allowed.
	private static int     countdownMissed= more; // number of wrong letters that are guessed

	public static void main(String arg[])
	{
		System.out.println("Welcome to hangman.");

		initialize();    // get random word from a list and convert to an array of characters

		System.out.println("I'm thinking of a "+wordString.length()+" letter word");
		System.out.println("You may mis-guess "+more+" letters before you lose.");
		System.out.println("");

		keepGuessing();  // loop : while still playing, or exit if won or lost.

		System.out.println("Thanks for playing...goodbye!");
	}

	/**
	* initialize() does 3 things at the start of the game:
	*   1. initializes and instantiates a list/array of possible words to be guessed
	*   2. identifies one random word from the list to be used as the secret word
	*   3. converts the string into an list/array of individual characters
	*/
	public static void initialize()
	{
		// here are the list of possible words
		String pw[]     = {"java", "computer", "program","health"};
		int randomIndex = (int)(Math.random()*pw.length);
		wordString      = pw[randomIndex];
		word            = wordString.toCharArray();  // convert to an array of characters
	}

	/**
	* keepGuessing() will repeat the following sequence:
	*   1. Ask player to guess a letter
	*   2. Check the player's guess against the each letter of the word and
	*      count the number of times the guessed letter was found in the word.
	*   3. Determine if the player has either won, lost, or will continue playing.
	*/
	public static void keepGuessing()
	{
		int winLosePlay = 0;    // -1="lose", 0="keep playing", 1="win"

		while (winLosePlay==0)  // while we keep playing
		{
			// user input...one letter at a time
			userInput    = getGuess();

			// number of times the user's letter is within word (0 if not found or already used)
			int numFound = checkGuessInWord();

			// determine if we win (1), lose (-1), or continue guessing (0)
			// based on the number of letters guessed correctly (or incorrectly) and how
			// many mis-guesses are remaining
			winLosePlay  = checkWinLoseContinue(numFound);
		}
	}

	/**
	*  getGuess() does the following :
	*    1. asks user to enter a letter to guess
	*    2. obtains a guess (i.e. text/letter) from person using keyboard (i.e. Scanner)
	*    3. increases the number of guesses attempted
	*    4. returns only the first letter of the guess
	*/
	public static String getGuess()
	{
		System.out.print("Guess a letter followed by  key: ");
		Scanner scan;
		scan = new Scanner (System.in);    // scan the console for any data typed in via keyboard
		String guess = scan.nextLine();
		numGuesses++;                      // just made one more guess
		String g = guess.substring(0,1);   // return only first letter of guess
		return g;
	}

	/**
	* checkGuessInWord() does the following :
	*    1. takes the first character of the guess entered by the user (i.e. letter)
	*    2. loops through each character in the word (i.e. character array) and :
	*       a) checks if any letter in word matches the letter from the user's guess
	*       b) replace each matching letter in word with a '*' to mark it as "guessed"
	*       c) count each matching letter in word that is replaced
	*    3. if no letters match then decrease the number of letters guessed
	*       to keep track of the number of missed guesses
	*    4. return the count of letters that matched in the word (0 if no matches).
	*/
	public static int checkGuessInWord()
	{
		int counter=0;
		char g1 = userInput.charAt(0);     // convert string's first letter to a character

		for (int i=0; i<word.length; i++)
		{
			if (g1 == word[i])
			{
				word[i] = '*';          // replace every character with a '*' to mark
				counter++;              // to identify that the character has been found
			}
		}

		if (counter==0) countdownMissed--;   // guess not found...decrease number guesses remaining
		return counter;
	}

	/**
	* checkWinLoseContinue() will check the following in sequence :
	*   1. checks if 1 or more letters were guessed correctly and print a "letter found" message
	*      otherwise print out a "letter not found" message
	*   2. print out a message stating number of wrong guesses that are remaining
	*   3. checks if the player has guessed ALL letters in word (returns +1) (i.e. winner)
	*      or has run out of guesses (returns -1)
	*      or should continue to play (returns 0)
	*/
	public static int checkWinLoseContinue(int found)
	{
		if (found>0)
		{
			System.out.print("Congrats, the letter "+userInput.toUpperCase()+" was found "+found+" times. ");
		}
		else
		{
			System.out.print("Sorry, the letter "+userInput.toUpperCase()+" was not found. ");
			System.out.println("You may mis-guess "+countdownMissed+" letters before you lose.");
		}
		System.out.println("");

		boolean win = checkIfWinner();
		if (win)
		{
			System.out.println("Congrats on finding "+wordString.toUpperCase()+" you win!");
			return 1; // we won
		}
		else if (countdownMissed == 0)
		{
			System.out.println("I'm sorry, you have lost.");
			System.out.println("The word you were looking for was "+wordString.toUpperCase());
		    return -1; // we lose
		}
		return 0;  // keep going
	}

	/**
	* checkIfWinner() will :
	*    1. loop through each letter in the word's array of characters
	*       and count the number of letters replaced with a '*' character.
	*    2. If the number of '*' characters is the same size as the word,
	*       return true (player has guessed all letters correctly)
	*       otherwise return false (not all letters have been correctly guessed)
	*/
	public static boolean checkIfWinner()
	{
		int allLettersCount = 0;
		for (int i=0; i<word.length; i++)
		{
			if (word[i]=='*') allLettersCount++;
		}
		if (allLettersCount == wordString.length())
		{
			return true;
		}
		return false;
	}
}