Created
May 6, 2019 22:54
-
-
Save ahmednasserpro/6823f81579336be56a3f4eaad4d45e71 to your computer and use it in GitHub Desktop.
***14.17 (Game: hangman) Rewrite Exercise 9.25. The program reads the words stored in a text file named hangman.txt. Words are delimited by spaces.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.io.*; | |
public class Test { | |
public static void main(String[] args) throws Exception { | |
File file = new File("hangman.txt"); | |
Scanner input = new Scanner(file); | |
List<String> words = new ArrayList<>(); | |
while (input.hasNext()) { | |
words.add(input.next()); | |
} | |
int randomIndex = (int) (Math.random() * words.size()); | |
String s = words.get(randomIndex); | |
char[] charsToDisplay = new char[s.length()]; | |
for (int i = 0; i < s.length(); i++) | |
charsToDisplay[i] = '*'; | |
char[] chars = s.toCharArray(); | |
int count = 0; | |
while (true) { | |
Scanner consoleInput = new Scanner(System.in); | |
System.out.print("(Guess) Enter a letter in word " + | |
String.valueOf(charsToDisplay) + ": "); | |
char letter = consoleInput.next().charAt(0); | |
switch (isLetterExists(chars, charsToDisplay, letter)) { | |
case 1: System.out.println(" " + letter + | |
" is already in the word"); | |
break; | |
case 2: System.out.println(" " + letter + " is not in the word"); | |
count++; | |
} | |
boolean isDone = true; | |
for (int i = 0; i < charsToDisplay.length; i++) { | |
if (charsToDisplay[i] == '*') { | |
isDone = false; | |
break; | |
} | |
} | |
if (isDone) { | |
System.out.println( | |
" The word is " + | |
String.valueOf(charsToDisplay) + | |
". You missed " + | |
count + (count > 1? " times": " time")); | |
System.out.print("Do you want to guess another word? Enter y or n> "); | |
char ch = consoleInput.next().charAt(0); | |
if (ch == 'n') | |
break; | |
} | |
} | |
} | |
static int isLetterExists(char[] chars, char[] charsToDisplay, char letter) { | |
for (int i = 0; i < chars.length; i++) { | |
if (letter == chars[i]) { | |
chars[i] = ' '; | |
charsToDisplay[i] = letter; | |
return 0; | |
} | |
} | |
for (int i = 0; i < chars.length; i++) | |
if (letter == charsToDisplay[i]) | |
return 1; | |
return 2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment