Scotty
Scotty

Reputation: 1

Number guessing game

I have been trying to make a number guessing game. It has a set of numbers and it is supposed to count and display the number of times you have guessed once you guess the correct number.

Currently the program runs the first 2 steps then just stops please help to solve this

import javax.swing.JOptionPane;  
import java.util.Scanner;
//Scott Timmerman TwentyQuestions

public class TwentyQuestions {

    public static void main(String[] args) {
        int number = 500000;
        int numberoftries = 0; 
        JOptionPane.showMessageDialog(null, "Scott Timmerman TwentyQuestions");
        Scanner input = new Scanner(System.in);
        int guess;
        boolean win = false;
        while (win == false) {

            JOptionPane.showInputDialog("Enter a number between 1 and 1,000,000" );
            guess = input.nextInt(); 
            numberoftries++; 
            if(guess == number) {
                win = true;
            }
            else if(guess > number){
                JOptionPane.showMessageDialog(null, "your guess " + guess + " was greater then the number");

            }
            else if (guess < number){ 
                JOptionPane.showMessageDialog(null, "your guess " + guess + " was less then the number");

            }
        }

        JOptionPane.showMessageDialog(null, "you lost!\n the number was " + number );
        JOptionPane.showMessageDialog(null, "you won!" + numberoftries + " tries");

        }


}
    ` 

Upvotes: 0

Views: 329

Answers (2)

sprinter
sprinter

Reputation: 27956

It looks as though you want the user to enter the next guess in the dialog box rather than at the console. If that's the case then you need to use the return value from JOptionPane.showInputDialog. The return value is then the text that the user entered before clicking the ok button. You will need to covert this to an integer using something like Integer.parseUnsignedInt which includes handling NumberFormatException (in case they type in something that isn't a number).

So something like:

try {
    String guessText = JOptionPane.showInputDialog("Enter your next guess");
    int guess = Integer.parseUnsignedInt(guessText);
} catch (NumberFormatException ex) {
    ...
}

Upvotes: 1

sziolkow
sziolkow

Reputation: 173

It stops because the program wait till you provide the value on the console not on the Java Dialogue. Switch to console and write there for example 500 and hit enter. This is the problem: Scanner input = new Scanner(System.in);

Upvotes: 0

Related Questions