import java.util.Random;
import java.util.Scanner;
public class RandomGame {
public static void main(String[] args) {
Random r = new Random();
int target = r.nextInt(100) + 1;
System.out.println("Number to guess is in my heart now.");
// System.out.println("Number to guess: " + target);
Scanner sc = new Scanner(System.in);
System.out.println("Please guess a number between 1 and 100.Your answer is:");
int input = sc.nextInt();
int times = 1;
while (input != target) {
if (input > target) {
System.out.println("Your answer is bigger than target!");
} else {
System.out.println("Your answer is smaller than target!");
}
times++;
System.out.println("Please try again! Tell me your answer:");
input = sc.nextInt();
}
System.out.println("You got the right answer! And it's the No." + times + " times you guess.");
}
}
输出示例:
Number to guess is in my heart now.
Please guess a number between 1 and 100.Your answer is:
50
Your answer is bigger than target!
Please try again! Tell me your answer:
25
Your answer is smaller than target!
Please try again! Tell me your answer:
37
Your answer is bigger than target!
Please try again! Tell me your answer:
30
Your answer is bigger than target!
Please try again! Tell me your answer:
28
Your answer is bigger than target!
Please try again! Tell me your answer:
26
You got the right answer! And it's the No.6 times you guess.