from random import randint
def csyx(maxValue):
# 随机生成一个整数
maxTimes=maxValue
value = randint(1, maxValue)
for i in range(maxTimes):
prompt = '请输入您猜的数字:'if i == 0 else '请再猜一次:'
# 使用异常处理结构,防止输入不是数字的情况
try:
x = int(input(prompt))
except:
print('必须输入整形数,且在数字1和', maxValue, '之间')
else:
if x == value:
# 猜对了
print('恭喜您,猜对了!')
break
elif x > value:
print('太大了!')
else:
print('太小了!')
else:
# 次数用完还没猜对,游戏结束,提示正确答案.
print('游戏结束,您失败了!')
print('正确答案是:', value)
csyx(10)
# 控制最大值和次数
运行结果:
public static void main(String[] args) {
cxyx(10);
}
public static void cxyx(Integer n){
Random rand = new Random();
int guessNum= rand.nextInt(n);
System.out.println(guessNum);
int resultType=0;
while (resultType==0) {
Scanner sc=new Scanner(System.in);
int cusNum = sc.nextInt();
if (cusNum < guessNum) {
System.out.println("小了");
} else if (cusNum > guessNum) {
System.out.println("大了");
} else{
System.out.println("猜对了");
resultType=1;
}
}