Difference between revisions of "Guess my Number"
From CompSciWiki
Line 22: | Line 22: | ||
String guess; //used to store the guess | String guess; //used to store the guess | ||
boolean correct = false; //loop variable initialized to false meaning our guess is incorrect | boolean correct = false; //loop variable initialized to false meaning our guess is incorrect | ||
+ | </pre> | ||
+ | To generate a random number between 1 and 10 we will need to use the following code. | ||
+ | <pre> | ||
+ | //(int)(Math.random() * 10 generates a random number from 0 to 9 | ||
+ | //to get a random number from 1 to 10 we need to add 1 | ||
+ | randNum = (int)(Math.random() * 10) + 1; | ||
</pre> | </pre> | ||
Line 27: | Line 33: | ||
<pre> | <pre> | ||
− | import java.lang.Math; | + | import java.lang.Math; //needed for Math.random |
− | import javax.swing.JOptionPane; | + | import javax.swing.JOptionPane; //needed for JOptionPane |
public class GuessMyNumber | public class GuessMyNumber |
Revision as of 09:28, 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 To generate a random number between 1 and 10 we will need to use the following code. //(int)(Math.random() * 10 generates a random number from 0 to 9 //to get a random number from 1 to 10 we need to add 1 randNum = (int)(Math.random() * 10) + 1; | ||
Code |