Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Cant figure out what I am doing wrong in my java guessing game program. The computer picks a number between 1 and 100 and the user is asked to guess it. User is prompted with too low or too high and asked to guess again until they get it right. My problem is that when you guess the number right, it will always say too low, but then if you type the same number again it will say correct.
package guessinggame;
import java.util.Scanner;
/**
*
* #author
*/
public class GuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int guesses; //number of users guesses
int housePick; //number the user must guess
int guess; //users guess
guesses = 0;
housePick = (int)((Math.random() * 100) +1 );
//sets housePick to random number from 1 to 100
System.out.println("I'm thinking of a number between 1 and 100") ;
//print "Im thinking of a nubmer between 1 and 100"
System.out.println("Can you guess what it is?");
//print "can you guess what it is"
System.out.println
("Enter a number from 1 to 100 (including 1 and 100)");
//prompt user to enter number
System.out.println("test " +housePick );
//Test: tells user the correct answer
do
{
guess = input.nextInt();
if (guess > housePick) //and if guess > housePick...
{
if ((guess - 10) <= housePick )
//and if guess is 10 numbers away from housePick...
{
System.out.println("Close, but too high. Try again.");
//print "close but too high, try again"
guesses = guesses+ 1 ;
}
else //if guess is not close and guess>housePick...
{
System.out.println ("Too high, try again.");
//then print "Too high, Try again"
guesses = guesses+ 1;
}
}
else //If guess<housePick
{
if ((guess + 10) >= housePick) //AND if guess is close to housePick
{
System.out.println ("close, but too low.") ;
//then print "close, but too low"
guesses = guesses + 1;
}
else//If guess isnt close to housePick and is less than housePick...
{
guesses = guesses+ 1;
System.out.println ("Too low.");//then print "too low"
}
}
}while (guess != housePick); //while guess doesnt = housePick...
guess = input.nextInt();
//save entered number as guess
guesses = guesses + 1;
System.out.println ("You win! It took you " + guesses + " guesses.");
//If guess = housePick print "Yout win! It took you (# of guesses)"
}
}
else //If guess<housePick
You're wrong with above condition, it is equivalent to guess <= housePick. it must be
else if( guess < housePick)
Also, Following block of code is executed when housePick == guess so there's not point of doing guess = input.nextInt(), You can simply say You Win.
}while (guess != housePick); //while guess doesnt = housePick...
// At this point, guess == housePick, why ask for input again????
// guess = input.nextInt();
//save entered number as guess
//guesses = guesses + 1;
You also have an extra input.nextInt() after the while:
}while (guess != housePick); //while guess doesnt = housePick...
guess = input.nextInt();
//save entered number as guess
Delete it
Lets see
Housepick = 87
guess = 87
if ((guess + 10) >= housePick) //AND if guess is close to housePick
{
System.out.println ("close, but too low.") ;
//then print "close, but too low"
guesses = guesses + 1;
}
hmm 87 + 10 IS greater than 87
And then it breaks the do/while loop and you are prompted again
Related
I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}
I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}
So I recently taught myself a little bit of JOptionPane. I am trying to make a Guessing Game which utilizes the JOptionPane. Currently this is my code:
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Random;
public class GuessingGameJOptionPane {
public static void main(String[] args) {
int guess, numberToGuess, numberOfTries = 0;
String input;
boolean win;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
numberToGuess = rand.nextInt(100);
JOptionPane.showInputDialog(null, null,"Please enter your name.", JOptionPane.QUESTION_MESSAGE);
win = false;
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE));
while(win == false){
numberOfTries++;
if(numberToGuess < guess1)
{
JOptionPane.showMessageDialog(null,"The number you guessed was to low. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else if(numberToGuess > guess1){
JOptionPane.showMessageDialog(null,"The number you guessed was to high. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "Congratulations you won. The number was " + numberToGuess + ". It took you " + numberOfTries, null, JOptionPane.INFORMATION_MESSAGE);
win = true;
}
}//Win == False
}//Main Method
}//Class
After I enter the number it continuously says your number is to low or high and keeps creating a new Pane. Any help will be appreciated Thanks.
Your problem specifically lives here:
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE));
while(win == false){ //Potential infinite loop begins here...
numberOfTries++;
if(numberToGuess < guess1)
{
JOptionPane.showMessageDialog(null,"The number you guessed was to low. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else if(numberToGuess > guess1){
JOptionPane.showMessageDialog(null,"The number you guessed was to high. Please try again" ,null , JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "Congratulations you won. The number was " + numberToGuess + ". It took you " + numberOfTries, null, JOptionPane.INFORMATION_MESSAGE);
win = true;
}
}//Win == False
This loop will only ever exit if win = true. However, this can only happen if a correct number is guessed. An incorrect number entry will cause the loop to continue infinitely, as the only time the user can actually enter the number is prior to loop entry. You can prove this by having your message dialog display the number of tries: you'll see each subsequent dialog will increase the tries by one.
Fortunately, the fix is easy:
while(win == false){
int guess1 = Integer.parseInt(JOptionPane.showInputDialog(null,null,"Guess a number between 1 and 1000", JOptionPane.QUESTION_MESSAGE)); //Moved this inside the loop
// ...rest is unchanged
I stopped programming for a while now. Probably around 4 years, and I was just looking to mess around with it, so I decided to make a high:low number guessing game. (guess a number 1-100, program says if your guess is too high or too low) and I completely forgot how I would go about:
a) Once the user guesses the correct number, asking if they want to play again
b) If they don't guess the correct number (too high or too low), the program lets them guess again.
I understand that you would need loops, but I just forgot about how I would go about them
package highlow;
import java.util.Random;
import java.util.Scanner;
public class guessing {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random();
int tries;
int correctNum = rand.nextInt(100);
System.out.println("enter a number 1-100");
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
}
else{
System.out.println("not a valid option");
}
}
}
You need to wrap everything in a while loop so that it keeps repeating until the user guesses correctly:
// Make the scanner, get the random number etc... Put all the setup and
// stuff you don't want to be repeated here
while (true) {
System.out.println("enter a number 0-99"); // Changed from 1-100 because rand.nextInt(100)
// returns a number between 0 and 99
// You can do correctNum += 1 to make it between 1 and 100
// But put this in before the while loop starts
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
break; // <---- Add this, this will make the loop stop when the
//player gets the answer correct and therefore the program will end
}
else{
System.out.println("not a valid option");
}
}
While loops repeat whatever is inside them until the statement inside their () is false. In our case the loop will go forever because true is inside the () but with the break statement, the loop will end when the user guesses correctly.
package highlow;
import java.util.*;
public class guessing
{
public static void main (String [] args)
{
boolean wantstoplay = true;
while(wantstoplay)
{
play();
System.out.println("Would you like to play again?");
Scanner kb = new Scanner (System.In);
if ((kb.nextLine().equals("yes") || (kb.nextLine().equals("Yes"))
wantstoplay = true;
else
wantstoplay = false;
}
}
public void play()
{
boolean playing = true;
int correctNum = (int) ((Math.Random() *100) + 1);
//selects random double from [1,101) and then rounds down
int tries = 0;
while (playing)
{
Scanner input = new Scanner(System.in);
System.out.println("enter a number 1-100");
int guess = input.nextInt();
if(guess < correctNum){
System.out.println("number is too low!");
tries++;
}
else if(guess > correctNum){
System.out.println("Number is too high!");
tries++;
}
else if(guess == correctNum){
System.out.println("correct!");
if (tries > 1)
System.out.println("Congrats, you guessed the right number. It only took you " + tries + " attempts!");
else
System.out.println("You guessed it first try! good job");
}
else{
System.out.println("not a valid option");
}
}
}
}
Above is some sample code that might be helpful.
I suggest making a play method, and then calling it in your main method.
This makes your code more organized and readable, because now you'll get the functionalities you desired without having 1 messy method with 2 loops in it.
You'll notice I included while loops rather than for loops. This is because while loops are ideal when you don't know how many times you're going to need to iterate.
The while in the main method checks to see whether the user would like another game. Notice that it assumes that the user wants to play at least one game. I did this by setting wantstoplay as true before we entered the loop, but this also could've been done with a do-while loop. For more, see (http://www.java-examples.com/do-while-loop)
The while in the play method checks to see whether the user needs to make another guess because he hasn't gotten the answer yet. Just like we can't know how many times the user wants to play before hand, we can't know how many guesses the user will take either.
Hope this helps you get back into programming!
In this program, the computer generates a random number (between 1-100) and the user attempts to guess it.
Runs until the user correctly guesses the number. Needs to print out the total number of tries it took before the number was guessed correctly.
Program runs fine, but there is a logical error. Nothing prints out when I correctly guess the number; the program just stops instead.
import java.util.*;
public class Problem3 {
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100)+1;
System.out.println(num); //prints out the random number so I know test works correctly
int count = 0;
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
console = new Scanner(System.in);
int guess = console.nextInt();
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else if( guess > num){ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{
count++;
System.out.println("You guessed correctly after " + count + " tries!");
}
}
}
}
Actually you never enter the else stage, because when the number is guessed, the while code won't execute and therefore the else code will never execute. So after that the number is guessed, so condition is false, exit while loop and System.out.print the Congrats message
Put this outside your while loop "at the end":
System.out.println("You guessed correctly after " + count + " tries!");
Here's what your code should look like:
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}
}
System.out.println("You guessed correctly after " + ++count + " tries!");
Your while loop condition becomes false when the correct number is guessed. This makes the else unreachable.
EDIT
Here is how I would have tackled your problem. If you find yourself repeating code, it usually means there is an opportunity for improvement. Not only is there less code, but it is easier to read and follow what is going on. I'm not trying to steal the answer (#AmirBawab found the issue first), but I am a big believer in not just making code that works, but code that can be maintained and read by others. Hopefully as you continue learning you will keep that in mind. Happy coding!
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int num = rand.nextInt(100) + 1;
int count = 0;
while (true) {
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
int guess = console.nextInt();
count++;
if (guess < num) {
System.out.println("Your guess is too low");
} else if (guess > num) {
System.out.println("Your guess is too high");
} else {
System.out.println("You guessed correctly after " + count + " tries!");
break;
}
}
console.close();
}