思路如下: (1)生成随机数字 (2)读取猜测数字 (3)猜测数字与随机数字进行比较,输出各个结果 代码如下:
import java.util.Random;
import java.util.Scanner;
public class GameNumber {
public static void main(String[] args) {
// 用Random实现生成随机数
Random random = new Random();
int gus = random.nextInt(100);
System.out.println(gus);
System.out.println("请开始你的表演:");
Scanner scanner = new Scanner(System.in);
// 用scanner.hasNextInt()方法实现多次读取Int型数据
while(scanner.hasNextInt()){
int a = scanner.nextInt();
if (a < gus) {
System.out.println("猜小啦!");
} else if (a >gus) {
System.out.println("猜大啦!");
} else {
System.out.println("猜对啦!");
break;
}
}
}
}
import java.util.Random; import java.util.Scanner; public class GameNumber { public static void main(String[] args) { // 用Random实现生成随机数 Random random = new Random(); int gus = random.nextInt(100); System.out.println(gus); System.out.println("请开始你的表演:"); Scanner scanner = new Scanner(System.in); // 用scanner.hasNextInt()方法实现多次读取Int型数据 while(scanner.hasNextInt()){ int a = scanner.nextInt(); if (a < gus) { System.out.println("猜小啦!"); } else if (a >gus) { System.out.println("猜大啦!"); } else { System.out.println("猜对啦!"); break; } } } }
结果演示: