- import java.util.Scanner;
- import java.util.Random;
- public class GuessRandomNumber
- {
- {
- //Create a new scanner object called input
- //Create a new random object called generator
- //Here we will count how many guesses the user has
- int guessCounter = 0;
- //This boolean is true if the user hasn't won
- boolean userHasNotWon = true;
- //This sets the number that the user is trying to guess to a number from 0-20
- int answer = generator.nextInt(20);
- //This while loop will run while the user hasn't won
- while(userHasNotWon == true)
- {
- //Here, we ask the user from between 0-20 and assign it to an int called guess
- int guess = input.nextInt();
- //If the guess is over twenty then we tell the user
- if(guess > 20) {
- }
- //If the guess is less than 0 then we tell the user
- if(guess < 0) {
- }
- //If the guess is in the right range then we check whether they were right or not
- if(guess >= 0 && guess <= 20) {
- //If the guess is too high then we tell the user and increment the guess counter by one
- if (guess < answer) {
- guessCounter += 1;
- }
- //If the guess is too low then we tell the user and increment the guess counter by 1
- if (guess > answer) {
- guessCounter +=1;
- }
- /**If the user guesses the right number then we tell them they won and
- tell them how many times they had to guess**/
- if (guess == answer) {
- userHasNotWon = false;
- }
- }
- }
- }
- }
This site is designed to spread the java loooove!!! If you want to get started on java coding then you've come to the right place. Just go to my tutorials page and it'll get you going right away. Thanks!!!
Tuesday, October 12, 2010
11. Explanation on GuessingRandomNumber class
Okay so I've just posted the class code here in case you didn't want to download it over at the source code page. Copy and paste it then look at the comments, they will explain what is going on!!!
Subscribe to:
Post Comments (Atom)
funny!i can't guess the right answer to what i programmed........good work on that....can you post more games please,so i can learn how the if,if else loop works and the boolean....thanks
ReplyDeleteOkay sure, I'm a bit busy but I'll try to get on it. Do you want any games in particular?
ReplyDeleteany game you think would be of help.thanks
ReplyDelete@ Bidex Games Games Games - Why not attempt the X and O in Java
ReplyDelete@ Dreguin Good, I like this