Java 猜数 升级版2

Java 猜数 升级版2

背景

好吧,猜数前两个问题解决了,所以快速进入下一个问题啦

题目简述

游戏开始之前,先提示输入玩家的个数,再提示输入猜数最大值,再开始游戏,玩家的名字就用player_1,player_2 … player_n。当然,还是猜数游戏

思路

第一步,既然是猜数,那首先就是要生成被猜的数,即是随机数randomNum;
第二步,按照题意,先输入玩家个数n,再输入猜数的最大值max;
第三步,玩家开始循环猜数,从player_1开始猜(即player_1输入数currentNum),判断输入数currentNum和随机数randomNum是否相等,相等则结束循环。
randomNum和currentNum的判断:
当输入数currentNum大于随机数randomNum(且小于max),提示“该随机数范围为0-currentNum”;当输入数currentNum小于随机数randomNum(且大于0)时,提示“该随机数范围为num-max”;当输入数currentNum等于随机数randomNum时,结束程序,输出“恭喜你,你猜对了”。
想到这里,突然会发现不对啊,判断不相等时的提示永远就是 0-XX或者XX-max或者0-max。例如:随机数为86,max=99,玩家1输入20,提示20-99,玩家2输入98,提示为0-98,这样就不行啊,因为希望的提示是20-98了。
那是什么问题呢?原来是我们需要更新猜数的范围,所以这里定义了左边边界leftNum和右边边界rightNum,用于更新猜数的范围。

代码块

import java.util.*; 

public class GuessingNumber {
	public static void main(String args[]){
		Scanner scan = new Scanner(System.in);
		Random rm = new Random();
		// 声明左右范围边界、输入数
		int leftNum = 0,rightNum, currentNum;
		// 声明当前玩家
		String nowPlayer;
		System.out.println("Please input the number of participants...");
		// 输入玩家人数
		int peopleNum = scan.nextInt();
		System.out.println("Please input the maximum number...");
		// 输入猜数的最大值
		rightNum = scan.nextInt();
		// 生成随机数
		int randomNum = rm.nextInt(rightNum), count = 0;
		System.out.println("game start...");
		while(true){
			System.out.println(leftNum + "-" + rightNum);
			nowPlayer = "player_" + (count+1);
			System.out.println(nowPlayer + " input: ");
			currentNum = scan.nextInt();
			if (currentNum == randomNum){
				break;
			} else if (currentNum > randomNum && currentNum < rightNum){
				rightNum = currentNum;
			} else if (currentNum < randomNum && currentNum > leftNum){
				leftNum = currentNum;
			}
			count = (count + 1) % (peopleNum);
		}
		System.out.println("Congratulations " + nowPlayer + ", you guessed it.");
		
	}
}

测试结果

这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/zcxbd/article/details/82464160