Assignment
University
California State UniversityCourse
COMP 182 | Data Structures and Program Design and LabPages
3
Academic year
2023
KauK
Views
21
import java . util .*; public class Lab3_1 { public static void main ( String [] args ) { String [] words = { "apple" , "oranges" , "write" , "that" , "instructor" }; Scanner stdin = new Scanner ( System . in ); boolean play = true ; while ( play ) { //Get random word int index = ( int )( Math . random ()* words . length ); String word = words [ index ]; hangman ( word ); System . out . print ( "Do you want to guess another word? Enter y or n: " ); play = stdin . next (). charAt ( 0 ) == 'y' ; } } public static void hangman ( String word ) { Scanner stdin = new Scanner ( System . in ); int missedGuesses = 0 ; char [] userWord = new char [ word . length ()]; char userLetter ; while ( true ) { //Check if user has already guessed the word boolean userWon = true ; for ( int i = 0 ; i < userWord . length ; i ++) { if ( userWord [ i ] != word . charAt ( i )) { userWon = false ; break ; } } if ( userWon ) { printResult ( word , missedGuesses ); break ; } //Check if the user has lost and exit program if ( missedGuesses > word . length ()) { printResult ( word , missedGuesses ); System . out . println ( "You lost!" ); System . exit ( 0 ); } System . out . print ( "Guess a letter in the word " ); //Print out current guessed letters for ( char c : userWord ) {
if ( c >= 'A' && c <= 'z' ) System . out . print ( c ); else System . out . print ( "*" ); } System . out . print ( " : " ); userLetter = stdin . next (). charAt ( 0 ); //check if the user has already typed the letter for ( char c : userWord ) { if ( userLetter == c ) { System . out . println ( userLetter + " is already in the word" ); break ; } } //Search if userLetter is in the word; return array of indexes where the letter is found int [] letterIndexes = new int [ word . length ()]; //-1 means not found Arrays . fill ( letterIndexes , - 1 ); boolean found = false ; for ( int i = 0 ; i < word . length (); i ++) { if ( userLetter == word . charAt ( i )) { letterIndexes [ i ] = i ; found = true ; } } //if letter is found; update the userWord array if ( found ) { for ( int letterIndex : letterIndexes ) { if ( letterIndex < 0 ) continue ; userWord [ letterIndex ] = userLetter ; } } else { //if not found; increment missedGuesses missedGuesses ++; System . out . println ( userLetter + " is not in the word" ); } } } public static void printResult ( String word , int missedGuesses ) { System . out . println ( "The word is " + word + ". You missed " + missedGuesses + " times." ); } }
Java Hangman Game: Guess Words and Test Your Skills
Please or to post comments