// GuessAWord.java (c) Kari Laitinen // http://www.naturalprogramming.com // 2012-11-03 File created. // 2012-11-04 Last modification. /* This program is a simple computer game in which the player has to guess the characters of a word, or the player may also try to guess the whole word. This program demonstrates: - the use of the standard StringBuffer class. StringBuffer objects are strings that can be modified, i.e., their characters can be changed. Standard String objects cannot be modified once they have been created. - the use of string methods such as charAt(), setCharAt(), length(), toUpperCase() */ import java.util.* ; class GuessAWord { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; System.out.print( "\n This is a GUESS-A-WORD game. \n" ) ; String word_to_be_guessed = "VIENNA" ; StringBuffer guessed_characters = new StringBuffer( "_________________________________________" ) ; // We'll shorten the StringBuffer string so that its length is equal // to the length of the word to be guessed. guessed_characters.setLength( word_to_be_guessed.length() ) ; // Now guessed_characters refers to a StringBuffer that contains // a string that has as many underscore characters as the // word to be guessed. boolean game_is_over = false ; while ( game_is_over == false ) { System.out.print( " " + guessed_characters + " " + "Give a character or word: " ) ; String player_input = keyboard.nextLine().toUpperCase() ; if ( player_input.length() == 1 ) { for ( int character_index = 0 ; character_index < word_to_be_guessed.length() ; character_index ++ ) { if ( word_to_be_guessed.charAt( character_index ) == player_input.charAt( 0 ) ) { guessed_characters.setCharAt( character_index, player_input.charAt( 0 ) ) ; } } if ( guessed_characters.indexOf( "_" ) == -1 ) { // "_" is not a substring in guessed characters. // This means that all characters have been guessed. game_is_over = true ; System.out.print( " " + guessed_characters + " Congratulations! \n\n" ) ; } } else if ( player_input.length() > 1 ) { // The player tried to guess the whole word. if ( player_input.equals( word_to_be_guessed ) ) { game_is_over = true ; System.out.print( "\n Congratulations! \n\n" ) ; } } else { game_is_over = true ; System.out.print( " \n Game over. \n\n" ) ; } } } }