Basic Java Hangman - java

I am just starting to learn Java as my first programming language.
In class we were assigned to make a basic Hangman game with the use of a while and for loops.
What I have so far
When the user inputs the first guess it does recognize that that characters that he/she guessed was corrected but just continues on and stating that I have guessed an incorrect letter!
Help would be very appreciated!! My question is what am I doing wrong in my code? I need the program to tell the user if his guess is right or wrong.
My code:
import cs1.Keyboard;
public class Hangman {
public static void main(String args[]) {
int guessCount = 0;
int correctGuess = 0;
boolean foundIt;
boolean solved;
char guess, answer;
String word;
System.out.println("Welcome to HangMan!");
System.out.println("Please enter a word for the opponent to guess!");
word = Keyboard.readString();
while (guessCount <= 6) {
System.out.println("Please enter any letter A-Z as your guess!");
guess = Keyboard.readChar();
for (int i = 0; i < word.length(); i++) {
if (guess == word.charAt(i)) {
System.out.println("You have guessed a correct letter!");
correctGuess++;
System.out.println("Correct Guess Count: "
+ correctGuess);
solved = false;
}
else if (guess != word.charAt(i)) {
System.out.println("Sorry! That is an incorrect guess! "
+ "Please try again!");
guessCount++;
System.out.println("Guess Count: " + guessCount);
solved = false;
}
}
if (correctGuess == word.length()) {
solved = true;
System.out.println("Congratulations! " +
"You have guessed the word!");
}
}
}
}
This is what I have so far and here is the output
Welcome to HangMan!
Please enter a word for the opponent to guess!
hello
Please enter any letter A-Z as your guess!
l
Sorry! That is an incorrect guess! Please try again!
Guess Count: 1
Sorry! That is an incorrect guess! Please try again!
Guess Count: 2
You have guessed a correct letter!
Correct Guess Count: 1
You have guessed a correct letter!
Correct Guess Count: 2
Sorry! That is an incorrect guess! Please try again!
Guess Count: 3
Please enter any letter A-Z as your guess!

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++;
}
}

You need to ask user input every time you finish an response to update the loop.
Your variable guess was never updated inside the loop, that is why it is running into infinite loop. You have update the guess variable as well inside the loop.

Related

One expected line of output is not printed

import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);

Guessing game with integer input validation and number of right guessed answers displayed Java

I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.
When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
Also If the user guesses correctly I have to keep track of how many they get right.
If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
At the end I have let the player know how many they got right out of 5.
This is my code so far
import java.util.Scanner;
public class Attempt11
{
public static void main(String args[]) {
int attempt = 1;
int userGuessNumber = 0;
int secretNumber = (int) (Math.random() * 6) + 1;
Scanner userInput = new Scanner(System.in);
System.out.println("Guess the next dice throw (1-6)");
do {
if (userInput.hasNextInt()) {
userGuessNumber = userInput.nextInt();
if (userGuessNumber == secretNumber) {
System.out.println("Congratulations you guessed right");
continue;
} else if (userGuessNumber < 1) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > 6) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
} else if (userGuessNumber < secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
}
if (attempt == 5) {
System.out.println("You have exceeded the maximum attempt. Try Again");
break;
}
attempt++;
} else {
System.out.println("Enter a Valid Integer Number");
break;
}
} while (userGuessNumber != secretNumber);
userInput.close();
}
}

How to show an input is invalid in this java code

I'm trying to make it so that when the user enters anything but y/n it'll say error and when they enter n it'll say have a great day. This is what I have so far, but I keep running into trouble.
This is the assignment:
Write a program that gets an integer from the user, say x, and then
prints an x by x square, and it prints that square x number of times.
For example, if the user enters 4, your program will print a 4x4
square four distinct times. Specifics:
The user enters a value 3-15. Input validation: only accept 3-15.
Allow the user to repeat the program if desired. Input validation: Y
or N only, but also allow lowercase entries.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
char answer = 'y';
while (answer == 'y' || answer == 'Y') {
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
}
answer = 'n';
while (answer == 'n' || answer == 'N') {
System.out.println("Program ending. Have a great day.");
}
keyboard.close();
}
}
You can solve this problem by only using one while loop. You use a break condition to inidicate that the loop should terminate (in your example if the user enters 'n').
Here is an example how I would try to solve this problem:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
boolean exit = false; // define the boolean variable
char answer = 'y';
while (!(exit)) { // start the while loop
if (answer == 'y' || answer == 'Y') { // if the user enters 'y' proceed with your code
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
} else if (answer == 'n' || answer == 'N') { // if the user enters 'n' exit the program and the loop
System.out.println("Program ending. Have a great day.");
exit = true;
} else { // display an error message when something else is typed
System.out.println("You entered an unvalid char, please answer by saying Y/N!");
answer = keyboard.next().charAt(0);
}
}
System.out.println("Reached end of program!");
keyboard.close();
}
Since this looks like homework I won't post the full answer but you can change the
while (answer == 'n' || answer == 'N')
to
if (answer == 'n' || answer == 'N')
Also close the scanner inside the if block above. The else case to the above is where you would throw the error. Hope its clear.
EDIT
Another thing I would like to add is that you can remove answer = 'n'; before the if condition above. That will already be read by
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);

Letter guessing game Java

I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={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};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}

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) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Do I really need this part?
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
System.out.println("You have 6 tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.println(" " + underscore[i] + " ");
}
System.out.println("Please enter your guess: ");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
}
}
}
}
// I've gotten a little lost here.
I know this is not right at all but I'm hoping for some tips. Thanks so much!!
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.
Couple things that need to be addressed here include giving the user the option to guess either a letter or a word, having the game go on as long as the user has not yet guessed the word yet, and checking to see if the user guessed a letter he or she has already guessed (this last thing is optional but is good practice for error checking). Think about the condition that will keep the game going. The game won't end until the user guessed 6 times or managed to successfully guess the word. To check these conditions after each guess, we can use a while loop. To see if the user guessed the word correctly, we can use a boolean variable to keep track of this,
boolean wordHasBeenGuessed = false;
while(!wordHasBeenGuessed && guesses < 6)
//this loop reads "while the word has not been guessed yet and the user has not exceeded 6 guesses
To give the user the option to guess either a letter or a word, we need to present two scenarios using if statements,
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals("letter"){
//do stuff to deal with this case here
}
else{
//do stuff to deal with this case here
}//of course this part can be customized anyway you'd like
In the end, it should look something like this,
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
boolean wordHasBeenGuessed = false;
int numOfLettersFound = 0;
while(!wordHasBeenGuessed && guesses < 6){
System.out.println("You have " + (6-guesses) + " tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals(letter)){
System.out.println("Enter your guess");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
numOfLettersFound++;
}
}
if(numOfLettersFound == wordToGuess.length()){
wordHasBeenGuessed = true;
}
}
else{
System.out.println("Enter your guess");
String answer = kybd.next();
if(answer.eqauls(wordToGuess){
wordHasBeenGuessed = true;
}
}
guesses++;
}
//after the while loop is finished, tell the user whether or not he/she has won or not
if(wordHasBeenGuessed){
System.out.println("You won");
}
else{
System.out.println("You lost");
}
}
}
If you have any questions, feel free to ask.

Categories