经典猜数游戏案例
方法一
public static void main(String[] args) {
//1.随机生成一个1-100的随机整数
Random rand = new Random();
int a = 1;
int b = 100;
int n = rand.nextInt(a, b + 1);
int i = 0;
//2.条件循环语句
while (true) {
if(i>=10){
System.err.printf("%d、游戏结束,智商太低,游戏:(%d)分。%n", i, 0);
break;
}
System.out.printf("请输入数字[%d-%d]:%n", a, b);
//3.键盘输入数字
int t = new Scanner(System.in).nextInt();
++i;
if (t == n) {
System.out.printf("%d、恭喜您,猜对了,你的游戏:(%d)分。%n", i, (100 - i * 10 + 10));
//退出循环语句
break;
} else if (t > n) {
System.out.printf("%d、太大了。%n", i);
} else {
System.out.printf("%d、太小了。%n", i);
}
}
}
方法二
public static void main(String[] args) {
//随机类
Random rand = new Random();
//键盘输入
Scanner sc = new Scanner(System.in);
//出题
int num = rand.nextInt(100) + 1;
int n = 0;
while (true) {
++n;
int temp = 0;
System.out.print("请输入数字[1-100]:");
if (sc.hasNextInt()) {
temp = sc.nextInt();
} else {
String s = sc.next();
if ("quit".contains(s)) {
sc.close();
System.out.printf("程序退出,游戏结束!%n");
break;
}
System.out.printf("输入有误%s,请重新输入!%n", s);
continue;
}
if (temp > num) {
System.out.printf("%d、太大了%n", n);
} else if (temp < num) {
System.out.printf("%d、太小了%n", n);
} else {
if (n == 1) {
System.out.printf("大神:你猜对了,你的游戏成绩:%d分", 100);
} else {
System.out.printf("%d、恭喜:你猜对了,你的游戏成绩:%d分", n, 110 - n * 10);
}
break;
}
}
}
}