本文实例为大家分享了java实现猜数游戏的具体代码,供大家参考,具体内容如下
有开始界面,可以设置范围,设置猜的次数
代码如下:
public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
System.out.println("----------猜数游戏----------");
System.out.println(" 1.开始游戏\n 2.游戏设置\n 3.退出游戏");
System.out.println("请输入:");
int[] arr = new int[3];
for (int i = 1; i < arr.length; i++) {
if (i < 4) {
arr[i] = sc.nextInt();
}
break;
}
int a = 0;
//开始界面
for (int i = 1; i < arr.length; i++) {
if (arr[i] == 1) {
System.out.println("开始游戏");
a = 1;
break;
} else if (arr[i] == 2) {
System.out.println("游戏设置");
a = 2;
break;
} else if (arr[i] == 3) {
System.out.println("退出游戏");
a = 3;
break;
} else System.out.println("错误输入");
}
//设置界面
int max = 100;
int min = 0;
int cishu = 5;
if (a == 2) {
System.out.println("设置范围");
System.out.println("最小值");
min = sc.nextInt();
System.out.println("最大值");
max = sc.nextInt();
System.out.println("设置猜的次数");
cishu = sc.nextInt();
//int randNum = rand.nextInt(max - min + 1) + min;
System.out.println("设置范围\n最小值为:" + min + "\n最大值为:" + max + "\n猜的次数为:" + cishu);
a = 6;
}
//设置后回到开始界面
if (a==6){
System.out.println("----------猜数游戏----------");
System.out.println(" 1.开始游戏\n 2.游戏设置\n 3.退出游戏");
System.out.println("请输入:");
for (int i = 1; i < arr.length; i++) {
if (i < 4) {
arr[i] = sc.nextInt();
}
break;
}
//开始界面
for (int i = 1; i < arr.length; i++) {
if (arr[i] == 1) {
System.out.println("开始游戏");
a = 1;
break;
} else if (arr[i] == 2) {
System.out.println("游戏设置");
a = 2;
break;
} else if (arr[i] == 3) {
System.out.println("退出游戏");
a = 3;
break;
} else System.out.println("错误输入");
}
}
//游戏界面
if (a == 1) {
int randNum = rand.nextInt(max - min + 1) + min;
System.out.println("我想了一个" + min + "到" + max + "的数,请你来猜:\n你有" + cishu + "次机会");
int i = 1;
for (; i <= cishu; ++i) {
System.out.println("第" + i + "次:");
int guess = sc.nextInt();
if (i < cishu) {
if (randNum >= guess) {
if (randNum <= guess) {
System.out.println("恭喜你猜对了!\n" + "该值是:" + randNum);
break;
} else System.out.println("你猜小了!");
} else System.out.println("你猜大了!");
} else System.out.println("你猜错了!\n该值是:" + randNum);
}
}
}
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。