用java编写一个简单的猜数字游戏:
import java.util.Random;
import java.util.Scanner;
public class GuessNumGame {
public static void main(String[] args) {
int[] level = {50, 100, 200, 500, 1000, 2000, 5000};
//
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int le = level[rand.nextInt(level.length)];
int num = rand.nextInt(1,le + 1);
int i = 0;
while (true){
++i;
System.out.println("请输入[1-" + le + "]:");
int t = sc.nextInt();
if (t > num){
System.out.printf("%d、\033[31m太大了\033[0m%n", i);
} else if (t<num) {
System.out.printf("%d、\033[31m太小了\033[0m%n", i);
} else {
System.out.printf("%d、\033[32m恭喜猜对了,游戏得%d分。\033[0m%n", i ,(110 - 10 * i));
break;
}
}
System.out.println("\033[33m游戏结束\033[0m");
}
}
运行结果: