Difference between revisions of "Guess my Number"

From CompSciWiki
Jump to: navigation, search
Line 2: Line 2:
  
 
|Problem= Generate a program where the computer chooses a random number between 1 and 10 and the user is continuously asked to guess it until they are correct.
 
|Problem= Generate a program where the computer chooses a random number between 1 and 10 and the user is continuously asked to guess it until they are correct.
 +
 +
You will need to review
 +
<link> </link>
  
  

Revision as of 21:05, 31 March 2010

Back to the Program-A-Day homepage

Problem

Generate a program where the computer chooses a random number between 1 and 10 and the user is continuously asked to guess it until they are correct.

You will need to review <link> </link>

 

SideSectionTitle

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

To get a random number in java you need to include <bold>import java.util.Random;</bold>

Random generator = new Random();
int randNum = generator.nextInt(10) + 1;
String guess;
boolean correct = false;

while(correct == false)
{
    guess = JOptionPane.showInputDialog("Enter a guess between 1 and 10:");
    if(Integer.parseInt(guess) == randNum)
    {
        correct = true;
        JOptionPane.showMessageDialog("You are correct");
    }
    else
        JOptionPane.showMessageDialog("You are incorrect");
}

Code

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

Back to the Program-A-Day homepage