本帖最后由 任文龙 于 2015-7-14 22:58 编辑
- import java.util.Scanner;
- import java.util.Random;
- class GuessNumber {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入数字(1-100):");
- //创建Random型变量,并调用nextInt方法
- Random r = new Random();
- int targetNumber = r.nextInt(100)+1;
-
- //无限循环,判断输入数字与目标数字的大小关系
- while (true) {
- int guessNumber = sc.nextInt();
- if (targetNumber>guessNumber) {
- System.out.println("你输入的"+guessNumber+"过小");
- }
- else if (targetNumber<guessNumber) {
- System.out.println("你输入的"+guessNumber+"过大");
- }
- else {
- System.out.println("恭喜!猜中了!");
- break;
- }
- }
- }
- }
复制代码
|