|
| 1 | +import java.util.Random; |
| 2 | +import java.util.Scanner; |
| 3 | + |
| 4 | +public class RandomWordGuessingGame { |
| 5 | + public static void main(String[] args) { |
| 6 | + String[] words = {"apple", "banana", "chocolate", "elephant", "giraffe"}; |
| 7 | + Random random = new Random(); |
| 8 | + String targetWord = words[random.nextInt(words.length)]; |
| 9 | + String currentGuess = maskWord(targetWord); |
| 10 | + int numberOfTries = 0; |
| 11 | + |
| 12 | + Scanner scanner = new Scanner(System.in); |
| 13 | + |
| 14 | + System.out.println("Welcome to the Random Word Guessing Game!"); |
| 15 | + System.out.println("Can you guess the word? Let's get started!"); |
| 16 | + |
| 17 | + while (!currentGuess.equals(targetWord)) { |
| 18 | + System.out.println("Current Guess: " + currentGuess); |
| 19 | + System.out.print("Enter a letter: "); |
| 20 | + String letter = scanner.next().toLowerCase(); |
| 21 | + |
| 22 | + if (letter.length() != 1 || !Character.isLetter(letter.charAt(0))) { |
| 23 | + System.out.println("Please enter a single letter."); |
| 24 | + continue; |
| 25 | + } |
| 26 | + |
| 27 | + if (targetWord.contains(letter)) { |
| 28 | + currentGuess = updateCurrentGuess(targetWord, currentGuess, letter); |
| 29 | + System.out.println("Good guess!"); |
| 30 | + } else { |
| 31 | + System.out.println("Sorry, that letter is not in the word."); |
| 32 | + } |
| 33 | + |
| 34 | + numberOfTries++; |
| 35 | + } |
| 36 | + |
| 37 | + System.out.println("Congratulations! You guessed the word '" + targetWord + "' in " + numberOfTries + " tries."); |
| 38 | + } |
| 39 | + |
| 40 | + // Mask the target word with underscores. |
| 41 | + private static String maskWord(String word) { |
| 42 | + StringBuilder maskedWord = new StringBuilder(); |
| 43 | + for (int i = 0; i < word.length(); i++) { |
| 44 | + maskedWord.append('_'); |
| 45 | + } |
| 46 | + return maskedWord.toString(); |
| 47 | + } |
| 48 | + |
| 49 | + // Update the current guess with correctly guessed letters. |
| 50 | + private static String updateCurrentGuess(String target, String currentGuess, String letter) { |
| 51 | + StringBuilder updatedGuess = new StringBuilder(currentGuess); |
| 52 | + for (int i = 0; i < target.length(); i++) { |
| 53 | + if (target.charAt(i) == letter.charAt(0)) { |
| 54 | + updatedGuess.setCharAt(i, letter.charAt(0)); |
| 55 | + } |
| 56 | + } |
| 57 | + return updatedGuess.toString(); |
| 58 | + } |
| 59 | +} |
0 commit comments