Simple HangMan game Implemented in Java
$begingroup$
This simple implementation of the HangMan game in Java is a side project, unlike the usual programs I write which are either school assignments or problems on coding websites.
It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String args) throws FileNotFoundException {
Scanner userGuess = new Scanner(System.in);
printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char wordCharArray = word.toCharArray();
System.out.println("It's time to guess the word!");
StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));
int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;
do {
System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");
String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);
if (isValidInput(userInput)) {
System.out.println("Your guess is: " + userInput);
if (!(containsUserInput(wordCharArray, userInput))) {
letterNotInWordMessage(userInput);
failedAttempts++;
} else if (containsUserInput(wordCharArray, userInput)){
letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;
}
} else {
System.out.println("Invalid input entered. Try again.");
}
totalAttempts = successfulAttempts + failedAttempts;
} while (!word.equals(gameWord.toString()));
if (word.equals(gameWord.toString())) {
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();
}
}
private static void printTitleScreen() {
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");
}
private static String printBlankSpaces(String word) {
return new String(new char[word.length()]).replace('', '-');
}
private static void letterNotInWordMessage(String letter) {
System.out.println("The letter " + letter + " is not in the word!");
}
private static void letterInWordMessage(String letter) {
System.out.println("The letter " + letter + " is in the word!");
}
private static int getMatchingIndex(char wordArray, String userGuess) {
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++) {
if (String.valueOf(wordArray[i]).equals(userGuess)) {
index = i;
}
}
return index;
}
private static boolean containsUserInput(char wordArray, String userGuess) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i] == userGuess.charAt(0)) {
return true;
}
}
return false;
}
private static boolean isValidInput(String userGuess) {
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0))) {
return true;
}
return false;
}
private static String getRandomWordFromFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";
while(fileScanner.hasNextLine()) {
fileContents = fileContents.concat(fileScanner.nextLine() + "n");
}
fileScanner.close();
String fileContentArray = fileContents.split("n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];
}
}
java hangman
New contributor
$endgroup$
add a comment |
$begingroup$
This simple implementation of the HangMan game in Java is a side project, unlike the usual programs I write which are either school assignments or problems on coding websites.
It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String args) throws FileNotFoundException {
Scanner userGuess = new Scanner(System.in);
printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char wordCharArray = word.toCharArray();
System.out.println("It's time to guess the word!");
StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));
int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;
do {
System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");
String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);
if (isValidInput(userInput)) {
System.out.println("Your guess is: " + userInput);
if (!(containsUserInput(wordCharArray, userInput))) {
letterNotInWordMessage(userInput);
failedAttempts++;
} else if (containsUserInput(wordCharArray, userInput)){
letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;
}
} else {
System.out.println("Invalid input entered. Try again.");
}
totalAttempts = successfulAttempts + failedAttempts;
} while (!word.equals(gameWord.toString()));
if (word.equals(gameWord.toString())) {
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();
}
}
private static void printTitleScreen() {
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");
}
private static String printBlankSpaces(String word) {
return new String(new char[word.length()]).replace('', '-');
}
private static void letterNotInWordMessage(String letter) {
System.out.println("The letter " + letter + " is not in the word!");
}
private static void letterInWordMessage(String letter) {
System.out.println("The letter " + letter + " is in the word!");
}
private static int getMatchingIndex(char wordArray, String userGuess) {
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++) {
if (String.valueOf(wordArray[i]).equals(userGuess)) {
index = i;
}
}
return index;
}
private static boolean containsUserInput(char wordArray, String userGuess) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i] == userGuess.charAt(0)) {
return true;
}
}
return false;
}
private static boolean isValidInput(String userGuess) {
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0))) {
return true;
}
return false;
}
private static String getRandomWordFromFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";
while(fileScanner.hasNextLine()) {
fileContents = fileContents.concat(fileScanner.nextLine() + "n");
}
fileScanner.close();
String fileContentArray = fileContents.split("n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];
}
}
java hangman
New contributor
$endgroup$
add a comment |
$begingroup$
This simple implementation of the HangMan game in Java is a side project, unlike the usual programs I write which are either school assignments or problems on coding websites.
It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String args) throws FileNotFoundException {
Scanner userGuess = new Scanner(System.in);
printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char wordCharArray = word.toCharArray();
System.out.println("It's time to guess the word!");
StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));
int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;
do {
System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");
String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);
if (isValidInput(userInput)) {
System.out.println("Your guess is: " + userInput);
if (!(containsUserInput(wordCharArray, userInput))) {
letterNotInWordMessage(userInput);
failedAttempts++;
} else if (containsUserInput(wordCharArray, userInput)){
letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;
}
} else {
System.out.println("Invalid input entered. Try again.");
}
totalAttempts = successfulAttempts + failedAttempts;
} while (!word.equals(gameWord.toString()));
if (word.equals(gameWord.toString())) {
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();
}
}
private static void printTitleScreen() {
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");
}
private static String printBlankSpaces(String word) {
return new String(new char[word.length()]).replace('', '-');
}
private static void letterNotInWordMessage(String letter) {
System.out.println("The letter " + letter + " is not in the word!");
}
private static void letterInWordMessage(String letter) {
System.out.println("The letter " + letter + " is in the word!");
}
private static int getMatchingIndex(char wordArray, String userGuess) {
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++) {
if (String.valueOf(wordArray[i]).equals(userGuess)) {
index = i;
}
}
return index;
}
private static boolean containsUserInput(char wordArray, String userGuess) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i] == userGuess.charAt(0)) {
return true;
}
}
return false;
}
private static boolean isValidInput(String userGuess) {
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0))) {
return true;
}
return false;
}
private static String getRandomWordFromFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";
while(fileScanner.hasNextLine()) {
fileContents = fileContents.concat(fileScanner.nextLine() + "n");
}
fileScanner.close();
String fileContentArray = fileContents.split("n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];
}
}
java hangman
New contributor
$endgroup$
This simple implementation of the HangMan game in Java is a side project, unlike the usual programs I write which are either school assignments or problems on coding websites.
It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String args) throws FileNotFoundException {
Scanner userGuess = new Scanner(System.in);
printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char wordCharArray = word.toCharArray();
System.out.println("It's time to guess the word!");
StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));
int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;
do {
System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");
String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);
if (isValidInput(userInput)) {
System.out.println("Your guess is: " + userInput);
if (!(containsUserInput(wordCharArray, userInput))) {
letterNotInWordMessage(userInput);
failedAttempts++;
} else if (containsUserInput(wordCharArray, userInput)){
letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;
}
} else {
System.out.println("Invalid input entered. Try again.");
}
totalAttempts = successfulAttempts + failedAttempts;
} while (!word.equals(gameWord.toString()));
if (word.equals(gameWord.toString())) {
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();
}
}
private static void printTitleScreen() {
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");
}
private static String printBlankSpaces(String word) {
return new String(new char[word.length()]).replace('', '-');
}
private static void letterNotInWordMessage(String letter) {
System.out.println("The letter " + letter + " is not in the word!");
}
private static void letterInWordMessage(String letter) {
System.out.println("The letter " + letter + " is in the word!");
}
private static int getMatchingIndex(char wordArray, String userGuess) {
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++) {
if (String.valueOf(wordArray[i]).equals(userGuess)) {
index = i;
}
}
return index;
}
private static boolean containsUserInput(char wordArray, String userGuess) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i] == userGuess.charAt(0)) {
return true;
}
}
return false;
}
private static boolean isValidInput(String userGuess) {
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0))) {
return true;
}
return false;
}
private static String getRandomWordFromFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";
while(fileScanner.hasNextLine()) {
fileContents = fileContents.concat(fileScanner.nextLine() + "n");
}
fileScanner.close();
String fileContentArray = fileContents.split("n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];
}
}
java hangman
java hangman
New contributor
New contributor
edited 2 hours ago
200_success
130k17153419
130k17153419
New contributor
asked 4 hours ago
King ColdKing Cold
111
111
New contributor
New contributor
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
King Cold is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215463%2fsimple-hangman-game-implemented-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
King Cold is a new contributor. Be nice, and check out our Code of Conduct.
King Cold is a new contributor. Be nice, and check out our Code of Conduct.
King Cold is a new contributor. Be nice, and check out our Code of Conduct.
King Cold is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215463%2fsimple-hangman-game-implemented-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown