dimanche 15 octobre 2017

Java Random number guessing game with dialog box

Okay, I know this one has been asked before but I just can't figure out what is going wrong. Here are my instructions:

"Write a program that generates a random number between 1 and 1000 inclusively. Then ask the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
Also, keep a count of the number of guesses that the user makes. When the user correctly guesses the random number, the program should display the number of guesses. Input and output should be done with Dialog and Message boxes. "

I have been working and reading all week on this and this is my second incarnation. I am at the point where my head is twisted around from all the reading. I get it to ask for a number in the dialog box and then nothing. What am I missing to keep the loop going? Please explain the what and why. Thanks in advance for looking.

import java.util.Scanner;        // Needed for the Scanner class.
import java.util.Random;         // Needed for the Random class.
import javax.swing.JOptionPane;  // Needed for JOptionPane.

/**
This program generates a random number guessing game.
*/

public class GuessingNumbersGame
{
public static void main(String[] args)
{
// Create an object and assign a whole random number 
// from 1 to 1000 to it.
int rnumber;`
Random randomNumbers = new Random();
rnumber = randomNumbers.nextInt(1000) + 1; 

// Ask the user to guess the random number.
String answer;
int guess; 
answer = JOptionPane.showInputDialog("Enter a whole  " +
"number between 1 and 1000.");
guess = Integer.parseInt(answer);
int guesses;
guesses = 0;                                                          

// Create a loop of user guesses versus the random number
// until the user answers correctly and keep track of the 
// number of times the user guesses. 
while (guess != rnumber);
{                                   
if (guess > rnumber)
{
JOptionPane.showMessageDialog(null,"Too high, try again.");
guess = Integer.parseInt(answer);
guesses++;
}            
if (guess < rnumber)
{                         
JOptionPane.showMessageDialog(null,"Too low, try again.");
guesses++;
}  
}       
while (guess == rnumber)
{                
guesses++;
JOptionPane.showMessageDialog(null,"Congratulations! The correct " +
"number is " + rnumber + ",and you had" + guesses + "guesses.");

}

System.exit(0);
}  
}




Aucun commentaire:

Enregistrer un commentaire