forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHangmangame.java
64 lines (56 loc) · 2.21 KB
/
Hangmangame.java
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
import java.util.Scanner;
public class HangmanGame {
private static String[] words = {"java", "programming", "hangman", "computer", "algorithm"};
private static String selectedWord;
private static String guessedWord;
private static int maxAttempts = 6;
private static int attemptsLeft = maxAttempts;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
selectWord();
while (true) {
System.out.println("Word: " + guessedWord);
System.out.println("Attempts left: " + attemptsLeft);
System.out.print("Enter a letter or the entire word: ");
String guess = scanner.nextLine().toLowerCase();
if (guess.length() == 1) {
processLetterGuess(guess.charAt(0));
} else if (guess.length() == selectedWord.length()) {
processWordGuess(guess);
} else {
System.out.println("Invalid input. Please enter a single letter or the entire word.");
}
if (guessedWord.equals(selectedWord)) {
System.out.println("Congratulations! You've guessed the word: " + selectedWord);
break;
} else if (attemptsLeft == 0) {
System.out.println("You've run out of attempts. The word was: " + selectedWord);
break;
}
}
scanner.close();
}
private static void selectWord() {
selectedWord = words[(int) (Math.random() * words.length)];
guessedWord = new String(new char[selectedWord.length()]).replace('\0', '_');
}
private static void processLetterGuess(char letter) {
boolean found = false;
for (int i = 0; i < selectedWord.length(); i++) {
if (selectedWord.charAt(i) == letter) {
guessedWord = guessedWord.substring(0, i) + letter + guessedWord.substring(i + 1);
found = true;
}
}
if (!found) {
attemptsLeft--;
}
}
private static void processWordGuess(String word) {
if (word.equals(selectedWord)) {
guessedWord = selectedWord;
} else {
attemptsLeft--;
}
}
}