Java exercise: Guessing Game
Practicing your craft is very important part of being a developer. Using Java, you need to create a guessing game where the computer will think of a random number between 1-100, and the player gets 10 turns to guess the number.
You will need to ask the user for input, and also you will need the computer to generate a random number. You need to limit the player`s turns to 10. If the player is successful in guessing the number, you can declare a winner and the game will end. If the player does not succeed in guessing the number, the game will end, and you need to tell the player what number was the computer thinking of.
Try it out. If you are stuck, scroll down for a solution.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.util.Random; import java.util.Scanner; public class GuessTheNumberGame { public static void main(String[] args) { int anyRandomNumber = (int) (Math.random() * 100) + 1; boolean isWinner = false; System.out.print("I`m thinking of a number between 1 and 100 (Including both).\n" + " Can you guess what it is?\n" + " Type a number: "); Scanner in = new Scanner (System.in); for (int i = 10; i >0; i--) { System.out.println("You have " + i + " guess(es) left. Take a guess: "); int yourGuess = in.nextInt(); if (anyRandomNumber > yourGuess) { System.out.println("Your guess is to low"); } else if (anyRandomNumber < yourGuess) { System.out.println("Your guess is to high"); } else { isWinner = true; break; } } if (isWinner) { System.out.println("You guess it right. You are the champion!"); } else { System.out.println("Game Over. You did not guess the number i was thinking "); System.out.println("The number i was thinking was " + anyRandomNumber); } } } |
You have a better solution, fell free to share it with everyone.
Happy coding!