Beginner Hangman Game
When you call
charPos = FindWord.indexOf(letter, charPos + 1);
you are setting charPos
back to -1
in the case where the letter only occurs once, not twice. You need to get rid of this.
Either
- use a different variable for the second position of the letter, OR
- write this into a loop, to allow for any number of occurrences of the letter, OR
- or set a boolean variable to indicate whether the letter was found; and use that to determine whether to add one to
incorrect
.
Basic Java Hangman
You compare the guess
to every character in the String
and then display the message for every character. Instead, you should write a method that returns a count of characters that match the input (this also handles words that have repeats of letters). So,
private static int countOf(String in, char ch) {
int count = 0;
for (char c : in.toCharArray()) {
if (c == ch) {
count++;
}
}
return count;
}
Then you can call it like,
guess = Keyboard.readChar();
int count = countOf(word, guess);
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;
Edit To do it without a second method you could use,
guess = Keyboard.readChar();
int count = 0;
for (char c : in.toCharArray()) {
if (c == guess) {
count++;
}
}
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;
And, since you haven't used the for-each
-
char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == guess) {
count++;
}
}
Creating simple hangman program in java, trouble with for loop
You could try it as follows:
move all the characters of secretWord to a map (key would be the character and the value would be incidences of that character in the string).
read the character from the keyboard and interate (basically, your logic).
Here is the code.
public static void main(String[] args) {
String secretWord = "frog";
Map<Character, Integer> mapOfLetters = new HashMap<>();
for (char c : secretWord.toCharArray()) {
int count = 1;
if (mapOfLetters.containsKey(c)) {
count = mapOfLetters.get(c) + 1;
}
mapOfLetters.put(c, count);
}
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0 && !mapOfLetters.isEmpty()) {
char guessedLetter = input.next().charAt(0);
if (mapOfLetters.containsKey(guessedLetter)) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
int count = mapOfLetters.get(guessedLetter) - 1;
if (count == 0) {
mapOfLetters.remove(guessedLetter);
} else {
mapOfLetters.put(guessedLetter, count);
}
} else {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
} else if(mapOfLetters.isEmpty()){
System.out.println("You Got It! The Word is: " + secretWord);
}
}
Simple game of hangman with two character arrays. They get six tries. First user enters a word the second user guesses the word through _ blanks
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
int wordLenToGuess = wordToGuess.length();
int unsuccessfulTries = 6;
while(wordLenToGuess >0 && unsuccessfulTries >0 ){
System.out.println();
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println();
System.out.println("You have " +unsuccessfulTries+ " tries to make a guess");
System.out.println("Please enter your guess: ");
//kybd.nextLine();
char guess = kybd.next().charAt(0);
boolean iscorrect = false;
for (int i = 0; i < underscore.length; i++) {
if(wordToGuess.charAt(i) == guess)
{
underscore[i] = guess;
wordLenToGuess--;
iscorrect = true;
}
}
if(!iscorrect)
unsuccessfulTries--;
}
if(wordLenToGuess == 0)
System.out.println("YOU WIN!! :)");
else System.out.println("Sorry! You Lose :(");
}
}
Algorithm:
Keep trying till either entire word is guessed or 6 incorrect tries.
If correct letter is guessed, fill in the blanks '_' else decrement the number of tries
Exit loop when either entire word is guessed or all 6 tries are used up.
Inform user if he wins or loses.
Hangman Java Programming
Array only ok
String[][] hangnanImages = {{"| | / / ||",
"| |/ / ||",
"| | / ||.-''-.",
"| |/ |/ _ _|",
"| | || '\'|",
"| | (\\ _O/'",
"| | .-'--'-.",
"| | / Y. .Y|| ",
"| | // | ||| ",
"| | // | . ||| ",
"| | ( '') | |('') ",
"| | ||- ||",
"| | || ||",
"| | || ||",
"| | || ||",
"| | / | | \\",
" ''''''''''|_`-' `-' |''''|"},
{"| | / / ||",
"| |/ / ||",
"| | / ||.-''-.",
"| |/ |/ _ _|",
"| | || '\'|",
"| | (\\ _O/'",
"| | .-'--'-.",
"| | Y. .Y|| ",
"| | | ||| ",
"| | | . ||| ",
"| | | |('') ",
"| | ||- ||",
"| | || ||",
"| | || ||",
"| | || ||",
"| | / | | \\",
" ''''''''''|_`-' `-' |''''|"}};//Put next hang man image in this one and similar and make as many as u want to your liking.
then what u can do you can make a method something like getHangmanImage(int num)
public String[] getHangmanImage(int number){
return hangManImages[number]; //this will return only a String[] not String[][]
}
//alternatively you can just do
public void printHangman(int number){
for(int i = 0; i < hangmanImages[number].length; i++){
System.err.println(hangmanImages[number][i]);
}
}
Now for the part MightyPork was talking about was this
String[] words = {"Word", "Components", ect ect}//however you want to put words in here.
Random rnd = new Random();
String rndWord = words[rnd.nextInt(words.length)];
Related Topics
How to Resolve Java.Lang.Noclassdeffounderror: Javax/Xml/Bind/Jaxbexception
How to Create Comma Separated String in Single Quotes from Arraylist of String in Java
Kafka: How to Delete Records from a Topic Using Java API
Adb Cannot Connect to Daemon At Tcp:5037
Password Validate 8 Digits, Contains Upper, Lowercase, and a Special Character
How to Sort Json Object in Java
How to Get Image Height and Width Using Java
How to Acknowledge Current Offset in Spring Kafka for Manual Commit
How to Exclude a Dependency from Parent'S Project in Maven
Create List of Object from Another Using Java 8 Streams
Java H2 In-Memory Database Error: Table Not Found
Broadcast Receiver Is Not Working When Application Is Removed from Background
Testing Two Json Objects for Equality Ignoring Child Order in Java
Escaping New Line Character Within SQL Query
Calculating the Angle Between Two Lines Without Having to Calculate the Slope (Java)
Notifydatasetchanged() Makes the List Refresh and Scroll Jumps Back to the Top
How to Compare Two Objects and Find the Fields/Properties Changed