In: Computer Science
You've devised a new twist on the traditional 'What number am I thinking of?' game to help your cousins learn their 7 times tables! Write a game that asks the user to guess the number you are thinking of. (For this game, the number will always be 42.)
The user is allowed 10 guesses, and makes a 'Mistake!' if they guess a number that isn't a multiple of 7. A user can make a maximum of one mistake, otherwise they lose the game. When the game is over, you should always print out That was fun.
Here is an example:
Guess a multiple of 7: 14
Nope!
Guess a multiple of 7: 32
Mistake! That number isn't a multiple of 7.
Guess a multiple of 7: 28
Nope!
Guess a multiple of 7: 86
Another mistake. Too bad.
That was fun.
Here is another example:
Guess a multiple of 7: 7
Nope!
Guess a multiple of 7: 14
Nope!
Guess a multiple of 7: 126
Nope!
Guess a multiple of 7: 133
Nope!
Guess a multiple of 7: 70
Nope!
Guess a multiple of 7: 77
Nope!
Guess a multiple of 7: 63
Nope!
Guess a multiple of 7: 35
Nope!
Guess a multiple of 7: 126
Nope!
Guess a multiple of 7: 77
Nope!
No guesses left!
That was fun.
If the user correctly enters 42, your program should print out You won! instead of Nope!, and then not ask for any more guesses. For example:
Guess a multiple of 7: 42
You won!
That was fun.
import java.util.Scanner;
public class GuessMultiple {
public static void main(String[] args) {
// Scanner class object to take
user input
Scanner scan= new
Scanner(System.in);
// Target value to be matched
int targetNumber = 42;
// Total guesses user get
int totalGuesses = 10;
// user input
int guessedNumber = -1;
// Total mistakes made by
user
int totalMistakes = 1;
// Iterate loop till
totalGuesses>0
while(totalGuesses>0) {
// Take user
input
// Decrement
totalGuesses by 1
System.out.print("Guess a multiple of 7: ");
guessedNumber =
scan.nextInt();
totalGuesses--;
// If number
matched, print message and exit program
if(guessedNumber==targetNumber) {
System.out.println("You won!\nThat was
fun.");
System.exit(0);
}
// Else if,
multiple of 7, display message
else
if(guessedNumber%7==0) {
System.out.println("Nope!");
}
// If not
multiple of 7 means first mistake
// increment
totalMistakes by 1 and print message
else
if(totalMistakes==1){
System.out.println("Mistake! That number isn't a
multiple of 7.");
totalMistakes+=1;
}
// If
totalMistakes is 2 means another mistake is made
// Print message
and exit
else
if(totalMistakes==2){
System.out.println("Another mistake. Too
bad.\nThat was fun.");
System.exit(0);
}
}
// After loop, means user lost and
guesses are complete
System.out.println("No guesses
left!\nThat was fun.");
}
}
OUTPUT-