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

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! ");
}

Related

Quitting while program is running when user presses 'q' then 'ENTER'

I want to give the user a choice to quit the program while the program is running whenever they feel like it. E.g. Press Q and ENTER at anytime to quit and end program.
I have a try and catch method but whenever I press Q and ENTER, it just displays whats in the catch part.
Here is the code:
public static void partB() {
//Code for partB goes here.
//Continues on with partA but with few changes
/* The number of multiplication problems should not be fixed. Instead,
the program should keep posing new multiplication problems until the user decides to quit by entering the letter "q".
The program should be able to deal with invalid input by the user.
It should ignore such input and restate the current multiplication problem.
*/
//Uses the imported Random function.
Random num = new Random();
//Initialises the minimum and maximum numbers.
int minNumber = 10; //Minimum number to start random
int maxNumber = 20; //Maximum number to start random
int counter = 0; //Counts the number of questions answered.
int correctAnswers = 0; //Counts the number of correct answers given.
final int numberOfQuestions = 0;
while(numberOfQuestions >= 0) {
//Generates a random integer between 10 and 20.
int randInt1 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Repeats for the 2nd integer to get the product of the two numbers.
int randInt2 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Initialise the Scanner function.
Scanner input = new Scanner(System.in);
//Output the Question.
System.out.println("What is " + randInt1 + " X " + randInt2 + "?" + " " + "(Press 'q' and ENTER to quit)");
//Waits for user input.
try {
int userInput = input.nextInt();
String quit = input.nextLine();
//If user input is 'q', quit program.
if(quit.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int answer = randInt1 * randInt2;
//Checks if the users input is correct.
if (answer == userInput) {
System.out.println("That is correct!");
correctAnswers++;
}
else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch(InputMismatchException e) {
System.out.println("You have entered something other than an integer or 'q'! Please try again with a different question!");
}
}
}
If you want to accept both a number and a letter, it is better to use nextLine(). First you check for q, and then parse to number, as follows (note that parseInt will throw a NumberFormatException):
try {
String userInput = input.nextLine();
// If user input is 'q', quit program.
if (userInput.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int userAnswer = Integer.parseInt(userInput);
int answer = randInt1 * randInt2;
// Checks if the users input is correct.
if (answer == userAnswer) {
System.out.println("That is correct!");
correctAnswers++;
} else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch (NumberFormatException e) {
System.out.println(
"You have entered something other than an integer or 'q'! Please try again with a different question!");
}

JAVA I don't understand Try-catch

This is my first time here. I'm starting to learn how to code, so I honestly hope this question I have is not something I can find over here! (I promise I searched for a while, but since I'm a noob in this topic, I didn't found anything understandable for me in order to resolve my doubt).
I'm doing a simple game in JAVA, in which the program generates a random number and the player has to guess the number generated.
When the player enters a number, the game displays a hint, saying if it is higher or lower than the number generated randomly.
The program itself works fine if you enter just numbers, but I want to add a try-catch statement to handle bad user input.
I tried using the statement as I show in my code, but I can't understand why it's not working properly, because when I enter something different of a number, the exception is catched and it prints on console the System.out.println(), but program terminates when this happens.
I would like to try-catch just to get the exception of entering not a number without terminating the program every time the exception is catched.
How can I fix this?
Thanks a lot for your help!
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
place try-catch inside the while loop and reinstantiate the scanner object (scan = new Scanner(System.in) inside the catch block.
while (guess != theNumber) {
try {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); // Reads the number typed on the
// keyboard by the player
count++; // Plus 1 every time a number is entered
System.out.println("You entered " + guess + ".");
if (guess < theNumber) { // If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if (guess > theNumber) { // If number entered is
// bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { // If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan = new Scanner(System.in);
}
}
You need to understand the working of the try-catch block. You don't need to surround the entire code within try. Just put that part of the code which causes an exception. So, in your case just surround guess = scan.nextInt(); with try and then catch an exception. Because, here this statement raises an exception when the input is not an integer. This way you can ensure that the user input is valid for each iteration of the while(guess != theNumber) loop.
Edit_1:
I removed the try-catch blocks from your code and added the following & it works fine for me:
try{
guess = scan.nextInt();} //Reads the number typed on the keyboard by the player
catch (InputMismatchException e){
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan.nextLine();
continue;
}

Java Guessing Game(Specifically JOptionPane)

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

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 simple program in JAVA? guessing game

Its my first year in college and i need to fix this program for my homework. How do i get the program to loop back for another input after the user has entered his/her first guess?
import javax.swing.JOptionPane;
import java.util.*;
public class Guessing {
public static void main(String[] args) {
final int MAX = 20;
int answer, guess, lowcount = 0, highcount = 0;
String sguess;
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
do {
sguess = JOptionPane.showInputDialog("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");
guess = Integer.parseInt(sguess);
if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is TOO HIGH!");
highcount++;
break;
} else if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is TOO LOW!");
lowcount++;
break;
}
}
while (guess != answer);
}
}
You need to remove the break statements in your 'do-while' loop.

Categories