Skip to content

Hangman Game #3

@Naman-2003

Description

@Naman-2003

package Learn_and_Build;

import java.util.Scanner;

public class Hangman {
//Create an array of words.
private static String[] words = { "apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew" };
//The word is then hidden by replacing each character with a dash ("-").
private static String word = words[(int) (Math.random() * words.length)];// Random number generator,This line of code should be executed only once.

//The word is then hidden by replacing each character with a dash ("-").
private static String hiddenWord = new String(new char[word.length()]).replace('\0', '-');
private static int count = 0;//The player has to guess the word by suggesting one letter at a time.
private static final int MAX_COUNT = 10  ;

public static void play() {
    Scanner input = new Scanner(System.in);
    for (int count = 0; count < MAX_COUNT && hiddenWord.contains("-"); count++) {
        System.out.println("Guess a  fruit letter:");
        System.out.println(hiddenWord);
        String guess = input.next();
        if (guess.length() != 1) {
            System.out.println("Please guess a single letter.");
            count--;
            continue;
        }
        char guessChar = guess.charAt(0);
        boolean found = false;
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == guessChar) {
                hiddenWord = hiddenWord.substring(0, i) + guessChar + hiddenWord.substring(i + 1);
                found = true;
            }
        }
        if (!found) {
            System.out.println("Sorry, that letter is not in the word.");
        }
    }
    if (hiddenWord.contains("-")) {
        System.out.println("You lost! The word was " + word);
    } else {
        System.out.println("Congratulations! You won with " + count + " wrong guesses.");
        System.out.println("Your Guess Word is:"+word);
    }
}

}
/** Hangman_base **/

package Learn_and_Build;

public class Hangman_base {
public static void main(String[] args) {
System.out.println("Welcome to Hangman!");
Hangman.play();
}

}
Footer
© 2023 GitHub, Inc.
Footer navigation
Terms
Privacy

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions