-
Notifications
You must be signed in to change notification settings - Fork 0
/
HangmanGame1
70 lines (57 loc) · 2.28 KB
/
HangmanGame1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
import java.util.Random;
public class HangmanGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String[] animals = {"lion", "elephant", "tiger", "giraffe", "zebra"};
String[] fruits = {"apple", "banana", "orange", "grape", "strawberry"};
String[] countries = {"usa", "canada", "india", "australia", "japan"};
System.out.println("Welcome to Hangman!");
System.out.println("Choose a category:");
System.out.println("1. Animals");
System.out.println("2. Fruits");
System.out.println("3. Countries");
int categoryChoice = scanner.nextInt();
scanner.nextLine(); // Consume newline
String[] chosenCategory;
switch (categoryChoice) {
case 1:
chosenCategory = animals;
break;
case 2:
chosenCategory = fruits;
break;
case 3:
chosenCategory = countries;
break;
default:
System.out.println("Invalid choice! Exiting the game.");
scanner.close();
return;
}
String wordToGuess = chosenCategory[random.nextInt(chosenCategory.length)];
char[] guessedLetters = new char[wordToGuess.length()];
for (int i = 0; i < guessedLetters.length; i++) {
guessedLetters[i] = '_';
}
int attempts = 7; // Number of attempts allowed
while (attempts > 0) {
System.out.println("\nCurrent Word: " + new String(guessedLetters));
System.out.println("Attempts left: " + attempts);
System.out.print("Enter your guess: ");
String guess = scanner.nextLine().toLowerCase();
if (guess.equals(wordToGuess)) {
System.out.println("Congratulations! You guessed the word: " + wordToGuess);
break;
} else {
System.out.println("Incorrect guess! Try again.");
attempts--;
}
}
if (attempts == 0) {
System.out.println("Sorry, you ran out of attempts. The word was: " + wordToGuess);
}
scanner.close();
}
}