I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.
Related
I am making a random generated number game. Computer randomizes a number 1-50 and user needs to guess that number in order to win. I need some help with using continue command in one line where program asks user to play the game over or quit the game.
Today we learned about continue and break commands. Professor made a little game to showcase using of continue and break. I copied the code to analyse it and deleted an continue command in one line just to see will it still work, and it did. Why did it work? I have marked the line with //<---HERE
while (true) {
Scanner input = new Scanner(System.in);
int randomNum = (int) (Math.random() * 50) + 1;
boolean found = false;
System.out.println("A number 1-50 is picked, try to guess it!");
System.out.println("--Testing purpose only--" + randomNum);
for (int i = 1; i < 6; i++) {
System.out.print(i + ". Try: ");
int chosen = input.nextInt();
if (chosen == randomNum) {
found = true;
System.out.println("You've guessed it");
break;
} else if (chosen < randomNum) {
System.out.println("Number you are guessing is higher");
} else {
System.out.println("Number you are guessing is lower");
}
}
if (found) {
System.out.println("Victory");
System.out.println("Guessing number was: " + randomNum);
} else {
System.out.println("Defeat! Guessing number was: " + randomNum);
}
System.out.print("Start over? (type \"yes\")");
String s = input.next();
if (s.equalsIgnoreCase("yes")) {
System.out.println("**************************");
**continue**; //<---HERE
} else {
System.out.println("End.");
break;
}
}
I am expecting an error if there is no continue command in marked place but there is no error and the program works fine.
It is the last statement of your infinite while loop. It has no effect whatsoever.
The continue line does not do anything in this case as it is the last statement in the loop.
It makes no sense for your code to generate an error just because you removed continue, the continue command will let you tell your program to skip to the next iteration. So without continue your code continues to execute normally.
I am writing a program where the user enters a number and the computer guesses the number.
I'm having trouble with my else/if statement inside of my while loop. The problem is it prints out "guess higher" but the computer does not always guess higher. I'm not sure how to go about this problem.
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(userGuess);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
System.out.println("Guess higher: ");
computerGuess = guess.nextInt(101);
System.out.println(computerGuess);
}
amountTries++;
}
The problem is it prints out "guess higher" but the computer does not
always guess higher. I'm not sure how to go about this problem.
You are specifying a hard-coded limit of 101 for the random number generation. But in the case where the computer guess is smaller than the user value, you need to have a random number generated between the computer guess and the user guess.
Replace
computerGuess = guess.nextInt(101);
with
computerGuess = guess.nextInt(userGuess - computerGuess) + computerGuess + 1;
If you are trying to build a program where computer guesses the number by binary search logic then your code is not going to work. Following code will perform binary search kind of logic.
int i=0;int j=101;
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
j=computerGuess;
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(j);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
i=computerGuess;
System.out.println("Guess higher: ");
//computerGuess = guess.nextInt(101);
computerGuess = guess.nextInt(j - i) +i;
System.out.println(computerGuess);
}
amountTries++;
}
PS: Not tested for corner cases. Code is just to provide a basic idea.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
so, for my Java class I need to make a HiLo game. I figured the game out on my own, but I wanted to take it a step further, and after the user completes the game(guesses the right number) I want to ask them if they would like to play again.
The problem is, I can't seem to figure out exactly how. I have tried several things and at the moment I'm trying to get them to enter either yes or no to continue playing the game. If someone could help me figure out what I'm doing wrong and explain it to me, that would be great. Thanks!
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int answer, guess;
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
if (guess == answer)
System.out.println("You got it! The number was " + answer);
//after initial game finishes, we ask if they want to play again.
System.out.print("Want to play again? ");
String again = scan.nextLine();
while (again != "no"){
System.out.println();
System.out.print("Great! lets play again.");
System.out.println("Take a guess(0-100 inclusive): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
if (guess == answer)
System.out.println("Your got it! The number was " + answer);
System.out.println("Want to play again? (0 for no, 1 for yes): ");
again = scan.nextLine();
}
}
System.out.println("Thanks for playing!");
}
}
The != operator does not check if two strings contain the same characters. What you want to do is:
while (again.equals("yes")) {
...
}
You should also try to put your game code inside another loop, so at the end of the game (still inside the loop) you can ask the player if they want to play again. If yes, the loop has to be executed again, otherwise it stops.
This way the player can play an infinite number of games and you don't need to duplicate your game code. Example (to get an idea of what the structure could look like):
// start with "yes" in order to enter the game loop initially
String again = "yes";
while(again.equals("yes")) {
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
System.out.println("You got it! The number was " + answer);
// ask them if they want to play again. only "yes" will start another game
System.out.println("Do you want to play again (yes/no)?");
again = scan.nextLine();
}
I am relatively new to java and this is my first time working with if else statements. I was attempting to make a basic game in which the user guesses a number between 1-3, and the program tells them if they are right or wrong. However, when I go to execute the program, when I type 1, the program does not respond and I have to use ctrl-E to end it. What am I doing wrong? When I enter values aside from 1, the program executes as I want it to by printing "Goodbye."
Here is my code:
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
Random rand = new Random();
System.out.println("Hey there! Want to play a game?");
System.out.println("\tIf yes, type 1");
System.out.println("\tIf no, type 2");
int ans1 = game.nextInt();
if (ans1 == 1) { // This is true, yet when I type 1, nothing happens.
int randomNum = rand.nextInt((3 - 1) + 1) + 1;
int guess = game.nextInt();
System.out.println("Great! I am thinking of an integer between 1 and 3. Guess what it is?");
if (guess == randomNum) {
System.out.println("Congradulations! You guessed correctly! The number was" + randomNum);
} else {
System.out.println("Sorry, your guess was incorrect. The number I was thinking of was" + randomNum);
}
} else {
System.out.println("Goodbye.");
}
}
}
This is my first time posting here, so I apologize if this question has been answered elsewhere.
Because if ans1=1, then it expects another input from user and checks if the guess and another input are same.
This is second input that it is waiting for
int guess = game.nextInt();
Input any number ,if the random number generated is equal to the number you added second time, it will return "Congradulations! You guessed correctly! The number was" else "Sorry, your guess was incorrect. The number I was thinking of was" with number
Instead of:
int guess = game.nextInt();
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
You should have them reversed.
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
int guess = game.nextInt();
This is my code below, i need to insert a play again function and a method that allows me to save the user name, number of attempts, number of successful attempts and the players best score to a text file! I have to repeat this bit of coursework to get back into my second year of university so any pointers about the code in generally would be greatly appreciated. I was never that good at programming so i'm badly stuck. This is my first time posting on this site as well due to recommendations of a friend so thanks in advance
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GuessingGame3 {
public static void main(String[] args)
{
Random generator = new Random(); //This is were the computer selects the Target
int guess;
int count = 0;
int Target;
String userName;
int answer;
boolean play = true;
int attempt = 6;
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)
{
Target = generator.nextInt(100) + 1;
System.out.println("Can you guess the number i'm thinking off? You will have "+ attempt +" 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();
count++;
attempt -= 1;
if (guess > Target)
System.out.println("Sorry! Your guess was too high! You have "+ attempt +" attempts left!"); //This is to help the player get to the answer
else
if (guess < Target)
System.out.println("Sorry! Your guess was too low! You have "+ attempt +" attempts left!"); //This is to help the player get to the answer
}
while(guess != Target && count <6);
if(guess == Target) {
System.out.println("Congratulations "+ userName + ", it took you "+ count +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
}
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
}
{
while(guess = Target || count > 6);
System.out.println("Would you like to play again "+ userName +"? [Y?N]:\n");
Answer = answer.nextLine();
if (Answer = "Y")
play = true;
else
if (Answer = "N")
System.out.println("Thanks for playing "+ userName +" :)! Please come back soon!");
}
break;
}
}
}
As the user above noted, you need this to be Answer == Y. YOu should not use strings, but characters. You should also use 'ToUpperCase()' to ensure that it will still work if the user inputs 'y' I recommend using .nextChar() instead of nextLine(), in case the user accidentily inputs a string with more than one character. for example if they bump the t button while pressing y.