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
[JOptionPane for input and ouput]
|
|
While and For Loops
|
Solution
To get a random number in java you need to include the following statement at the beginning of your source code. import java.util.Random;
|
Code
Solution Code
import java.lang.Math.*;
import javax.swing.JOptionPane;
public class GuessMyNumber
{
public static void main(String [ ] args)
{
int randNum = (int)(Math.random() * 10) + 1;
String guess;
boolean correct = false;
while(correct == false)
{
guess = JOptionPane.showInputDialog("Enter a guess between 1 and 10:");
if(guess != null)
{
if(Integer.parseInt(guess) == randNum)
{
correct = true;
JOptionPane.showMessageDialog(null, "You are correct", "", JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "You are incorrect", "", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
|
Back to the Program-A-Day homepage