Java Guessing Game(Specifically JOptionPane) - java

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

Related

Having problems with my random number guess game

I need help with my java code!
Want it to loop threw everything till the user put in the right number. When the user put in wrong number it should say "type in a different number". When the user put in the right number it should say "congrats you won".
But till then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
String number;
JOptionPane.showMessageDialog(null, "Welcome to the guessing game!" + "\nYou gonna guess a number between 1 and 20." + "\nHOPE YOU LIKE IT!:)");
Random amount = new Random();
int guessnumber = anount.nextInt(20);
int random;
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
random = Integer.parseInt(number);
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
if (random < guessnumber){
number = JOptionPane.showInputDialog("Your number is to high :(" + "\nType in a new lower number!");
random = Integer.parseInt(number);
}else if (random > guessnumber){
number = JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
random = Integer.parseInt(number);
}
}
}
That is because your only iterative statement is only displaying "You won!..etc":
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
Enclose the other codes below your while-loop to include them within the while loop. If you indent your codes properly, you should be able to spot your own problem. This is what you are looking for:
while (random != guessnumber){
//prompt for user input
if (random < guessnumber){
//Show Message "Your number is too low...
}
else if (random > guessnumber){
//Show Message "Your number is too high..."
}
else{ //got the number
//Show Message "you won!.."
}
}

How to fix this basic program? Java do-while loop

I am writing this guessing game, which enables the user to enter a number as the maximum number.
The random generator will then pick a number between 1 and the max number entered by the user.
It will save and display the number of high guesses and low guesses.
The problem I am having is looping the program and validating.
I can not get the program to loop back after a user has entered the wrong input, i.e. not an integer.
I want it to loop back for another guess after displaying an error message.
I am using a try/catch but after the error message the program does not allow the user to enter another number to continue the game.
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! Please keep your number less than 10,000.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
Ran it on my machine, and it loops back fine. It is broken though; guess is 0 by default, and you continue executing the code after the exception. If it happens that the random number is 0, the program will exit as it's the correct guess. Assuming something like this is happening on your machine?
You also haven't put the protecting logic around the initial "what's your max number" bit.
Use continue; in the try catch.
the code will be like
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
continue;
}
While I can't see the problem you are describing, may I suggest that you put the comparison code inside the try block, so that you can be sure the guess variable will be set properly before doing any comparison:
try {
guess = Integer.parseInt(sguess);
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}

I need advice to fix my HighLow code in java

Im fairly new to java and im having trouble getting this to loop? The code works fine, its just that after the user guesses correctly the code stops.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
while (true) {
System.out.println("Hi! Please enter a number between 1-100! (if you would like to quit, please press -1)");
int guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}
}
}
I'm not entirely sure what you're asking, however, from what I can understand, you are looking to get your game to loop continuously until the user wants to stop playing. So what you are looking for is a method which gives the user a choice whether they want to play again. My suggesting is using boolean. The following code demonstrates this for your example:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
private static boolean playAgain(){
Scanner sc = new Scanner(System.in);
String usrInput = "";
System.out.println("Play again? (Y/N)");
usrInput = sc.next();
if(usrInput.equalsIgnoreCase("Y")){
return true;
}
else if(usrInput.equalsIgnoreCase("N")){
return false;
}
else{
return false;
}
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
int guess1 = 0;
do{
do{
System.out.println("Please guess a number between 1-100!");
guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}while(guess1 != correctNum);
correctNum = random.nextInt(100);
NumberOfTries = 0;
}while(playAgain() == true);
}
}
Read more about methods here.
Read more about the boolean data type here.
Your final else appears to be missing a break. Like
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
break; // <-- add this.
}
or you might make that the while condition. Something like,
int guess1 = -1;
while (guess1 != correctNum) {
System.out.println("Hi! Please enter a number between 1-100! "
+ "(if you would like to quit, please press -1)");
guess1 = input.nextInt();
if (guess1 == (-1)) {
break;
}
NumberOfTries++;
if (guess1 < correctNum) {
System.out.println("The number inserted is too low!");
} else if (guess1 > correctNum) {
System.out.println("The number inserted is too high!");
} else if (guess1 == correctNum) {
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
}
}
Does it really stop after guessing it right ?

logical error with random number guessing game

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();
}

java guessing game runs but doesnt run correctly [closed]

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

Categories