Difference between revisions of "Guess my Number"

From CompSciWiki
Jump to: navigation, search
Line 1: Line 1:
 
{{1010PrAD|ProblemName=Guess my Number
 
{{1010PrAD|ProblemName=Guess my Number
  
|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. Use the following guidelines in coming up with a solution:
 
+
* [[https://webmail.cs.umanitoba.ca/mediawiki/index.php/Input/Output_using_JOptionPane JOptionPane for input and ouput]]
You will need to review
+
* [[Math Methods|Math.random()]] for generating the random number
[[https://webmail.cs.umanitoba.ca/mediawiki/index.php/Input/Output_using_JOptionPane JOptionPane for input and ouput]]
+
* [[While Loops|While loop]] for continuously asking for a guess until right
 +
* Boolean variable for indicating when the while loop is done
  
 
|SideSectionTitle=While and For Loops
 
|SideSectionTitle=While and For Loops
Line 11: Line 12:
 
[[Image:Wiki_loops03.jpg|center]]<BR>
 
[[Image:Wiki_loops03.jpg|center]]<BR>
  
|Solution=To get a random number in java you need to include the following statement at the beginning of your source code. <pre>import java.util.Random;</pre>
+
|Solution=To use Math.random() and JOptionPane you will need to include the following import statements.
 +
<pre>
 +
import java.lang.Math; //needed for Math.random
 +
import javax.swing.JOptionPane; //needed for JOptionPane
 +
</pre>
 +
We are also going to need 3 variables; int randNum, String guess, boolean correct.
 +
<pre>
 +
int randNum; //used to store the randNum we generate
 +
String guess; //used to store the guess
 +
boolean correct = false; //loop variable initialized to false meaning our guess is incorrect
 +
</pre>
  
 
|SolutionCode=
 
|SolutionCode=
  
 
<pre>
 
<pre>
import java.lang.Math.*;
+
import java.lang.Math;
 
import javax.swing.JOptionPane;
 
import javax.swing.JOptionPane;
  

Revision as of 09:21, 8 April 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. Use the following guidelines in coming up with a solution:

 

While and For Loops

Wiki loops03.jpg

Solution

To use Math.random() and JOptionPane you will need to include the following import statements.

import java.lang.Math; //needed for Math.random
import javax.swing.JOptionPane; //needed for JOptionPane

We are also going to need 3 variables; int randNum, String guess, boolean correct.

int randNum; //used to store the randNum we generate
String guess; //used to store the guess
boolean correct = false; //loop variable initialized to false meaning our guess is incorrect

Code

Solution Code

Back to the Program-A-Day homepage