Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Guessing Game

807606Apr 19 2007 — edited Apr 19 2007
Hi everyone, I am in my first unit of computer science amd trying to put together a guessing game which is supposed to repeat (either when all the users guesses run out or they correctly guess the number) untill the user opts out. I have written up the code and it works very well apart from one little snag. when the program repeats it is supposed to repeat from the stage of being asked "would you like to guess a number between 1 and 10" but instead it repeats at the next box "How many guesses would you like" I cannot figure out how to change it so any help at all would be very very very greatly appreciated.
(Code is below).

import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Random;

/**
* Guessing game for correct number.
*
* @author (Simon Orazi)
* @version (26/03/07)
*/
public class Assesment2
{
public static void main(String[] args)
{
int number; // a Random number between 1 & 10
String input; // To hold user's input
int usersAnswer; // user's guess
char repeat; // whether user wishs to continue
int amount; // number of guesses user wishs to have

// create a scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

// Create Random object class.
Random randomNumbers = new Random();

// get random number between 1 & 10.
number = randomNumbers.nextInt(10)*1;

// See whether user wishs to guess number.
input = JOptionPane.showInputDialog("Do you want to Guess " +
"a number between 1 and 10?");
repeat = input.charAt(0);
while (repeat == 'y' || repeat == 'Y')
{
// Get number of guesses user wishs to have.
input = JOptionPane.showInputDialog("How Many Guesses " +
"do you want");
amount = Integer.parseInt(input);

// get amount of guesses.
for (int count = 1; count <= amount; count++)
{
// prompts user to guess secret number.
input = JOptionPane.showInputDialog("Guess Number " + count);
usersAnswer = Integer.parseInt(input);

// determine whether the user guessed correctly.
if (usersAnswer == number)
{
JOptionPane.showMessageDialog(null, " You got it!" + "Good guess!");
break;
}
else
{
JOptionPane.showMessageDialog(null, "That is not correct, Sorry. ");
if (count == amount)
{
JOptionPane.showMessageDialog(null, "The number was " + number);


System.exit(0);
}
}
}
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 17 2007
Added on Apr 19 2007
3 comments
389 views