Write a program to generate a random number between 1 – 100 and keep it as a secret number. The program will then check if a user can guess the secret number. The user can continue guessing the number until the number is found or the user can enter 0, which will terminate the program.
Each time the user makes a guess, the program will report as below:
- Way Too High or Way Too Low (more than 30 off)
- High or Low (between 10 and 30 points off)
- A Little High or A Little Low (less than 10 points off)
If secret number is 74 and the user enters 26, the program will print "Way too Low". If the user then says 65, then the program will print "A Little Low
I'm getting stuck on the if statements, maybe my structure isn't correct. I'm not sure .
import java.util.Scanner;
public class SecretNumber {
public static void main(String[] args){
int random1, answer;
Scanner input = new Scanner(System.in);
random1 = (int)(Math.random()*10);
System.out.print(random1);
System.out.println("Guess the number");
answer = input.nextInt();
while(answer != 0) {
if (answer > (random1 + 30)){
System.out.println("Way to high");
}
else if ( answer > ( random1 - 30)){
System.out.println("Way to low");
}
else if (answer > random1 + 10 && answer < random1 + 30){
System.out.println("High");
}
else if (answer > random1 - 10 && answer < random1 - 30 ){
System.out.println("Low");
}
else if ( answer > random1 + 10){
System.out.println("A little high");
}
else if ( answer < random1 - 10){
System.out.println("A little low");
}
else if ( answer == random1){
System.out.println("That is correct");
System.exit(0);
}
else {
System.out.println("Guess the number");
answer = input.nextInt();
}
}
}
}
random1 = (int)(Math.random()*10);will give you0 <= random1 < 10- Reinstate Monica -- notmaynard