Having problems with my random number guess game - java

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!.."
}
}

Related

Random number of questions on game over screen on each run in arithmetic quiz game

I'm developing a game where the player does random types of basic arithmetic questions. When it displays the results when the game ends, it will display a message: "You answered %d questions with %d total attempts, your score is %.1f%%". However, when the user enters a value that is not an integer for their desired number of questions, the number of attempts made and the number of questions is different every time. The number of questions and the number of attempts is always the same, so it will always output a score of 100%. Inversely, when the user does enter an integer the first time they are prompted for the number of questions they want to do, the output for the percentage score at the end of the game will be "0.0%" if they answer incorrectly even once.
I have tried using try blocks inside of the try block to catch a NumberFormatException, as this only happens if they enter a value that is not an integer.
public static void randomArithmeticGame()
{
//RNG
int randNum;
boolean isValidInput = false;
boolean isInRange = false;
JOptionPane.showMessageDialog(null, "Welcome to the random arithmetic test", "Welcome", JOptionPane.INFORMATION_MESSAGE);
Addition a;
Subtraction s;
Multiplication m;
int ans;
while(!isValidInput)
{
try
{
int numberOfQuestions = Integer.parseInt(JOptionPane.showInputDialog(null, "How many questions would you like? (-1 to return to main menu)", "How many questions", JOptionPane.INFORMATION_MESSAGE));
while(!isInRange)
{
if(numberOfQuestions == -1)
{
//get out of loop if user enters -1 and go to bottom of block
break;
}
//do this while the number is not in range
if(numberOfQuestions > 10 || numberOfQuestions < 1)
{
//tell user that the number entered is out of range
JOptionPane.showMessageDialog(null, "Number of questions is not between 1 and 10, Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
try
{
numberOfQuestions = Integer.parseInt(JOptionPane.showInputDialog(null, "How many questions would you like? (-1 to return to main menu)"));
}
catch(NumberFormatException exception)
{
//catch exception
JOptionPane.showMessageDialog(null, "Number entered was not an integer. Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}
}
else
{
//if number is in range then break out of loop
isInRange = true;
isValidInput = true;
}
}
for(int i = 0; i < numberOfQuestions; i++)
{
randNum = (int)(Math.random()*3 + 1);
if(randNum == 1)
{
//generate addition if rng is 1
a = new Addition();
ans = a.getAnswer();
a.checkAnswer(ans);
}
if(randNum == 2)
{
//generate subtraction if rng is 2
s = new Subtraction();
ans = s.getAnswer();
s.checkAnswer(ans);
}
if(randNum == 3)
{
//generate multiplication if rng is 3
m = new Multiplication();
ans = m.getAnswer();
m.checkAnswer(ans);
}
}
}
catch(NumberFormatException exception)
{
//catch exception
JOptionPane.showMessageDialog(null, "Number entered was not an integer. Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}
}
int finalScoreQuestionNum = Addition.getNumberOfAdditionQuestions() + Subtraction.getNumberOfSubtractionQuestions() + Multiplication.getNumberOfMultiplicationQuestions();
int finalScoreResponseNum = Addition.getNumberOfResponses() + Subtraction.getNumberOfResponses() + Multiplication.getNumberOfResponses();
double finalScorePercentage = (finalScoreQuestionNum/finalScoreResponseNum)*100.0;
String finalScoreMessage = String.format("You answered %d questions with %d total attempts, your score is %.1f%%", finalScoreQuestionNum, finalScoreResponseNum, finalScorePercentage);
//show user how mantt questions they did, number of attempts they made, as well as their final score and percentage
JOptionPane.showMessageDialog(null, finalScoreMessage, "Results", JOptionPane.INFORMATION_MESSAGE);
}
The output should show the number of questions the user did, the number of attempts they made, and their percentage score. But the percentage and the number of attempts are the same only if the user doesn't enter an integer for the number of questions they want to do at the beginning of the game.
The problem is you are dividing int in finalScoreQuestionNum/finalScoreResponseNum.
If some value 0 < x < 1 results in the division. It will be 0. That's why you are always getting 0% when one of it is wrong i.e 99/100 will yield 0.
The decimal part is ignored.

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 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

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

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

Categories