Difference between revisions of "Guess my Number"
From CompSciWiki
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]] | |
− | + | * [[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 | + | |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
ProblemGenerate 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 | |
---|---|---|
SolutionTo 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 |