-
Notifications
You must be signed in to change notification settings - Fork 0
/
HangmanGame
49 lines (40 loc) · 1.62 KB
/
HangmanGame
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
import java.util.Random;
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = {"java", "hangman", "programming", "computer", "coding"};
Random random = new Random();
String wordToGuess = words[random.nextInt(words.length)];
char[] guessedWord = new char[wordToGuess.length()];
for (int i = 0; i < guessedWord.length; i++) {
guessedWord[i] = '_';
}
int attempts = 6; // Number of attempts allowed
boolean gameOver = false;
while (!gameOver) {
System.out.println("Word to guess: " + new String(guessedWord));
System.out.println("Attempts left: " + attempts);
System.out.print("Enter a letter: ");
char guess = scanner.next().charAt(0);
boolean correctGuess = false;
for (int i = 0; i < wordToGuess.length(); i++) {
if (wordToGuess.charAt(i) == guess) {
guessedWord[i] = guess;
correctGuess = true;
}
}
if (!correctGuess) {
attempts--;
}
if (attempts == 0) {
System.out.println("Sorry, you ran out of attempts. The word was: " + wordToGuess);
gameOver = true;
} else if (new String(guessedWord).equals(wordToGuess)) {
System.out.println("Congratulations! You guessed the word: " + wordToGuess);
gameOver = true;
}
}
scanner.close();
}
}