1.游戏运行时产生一个0-n之间的随机整数(n为控制台输入的正整数),如果输入的n不符合要求,则提示,并要求重新输入。
2.要求用户从控制台输入0-n之间的正整数,若输入的数字比产生的数字小,则输出:“太小了,再大一点”;若输入的数字比产生的数字大,则输出:“太大了,再小一点”,若输入不符合要求,则输出:“输入错误,请输入正确的数字!”,若输入的数字和产生的数字相等,则输出:“恭喜你,猜对了”然后退出程序。若用户猜了10次还未猜对,则输出:“你太笨了,下次再来吧”,然后退出程序。
3.要求必须进行异常处理,增强程序的容错性。
import java.util.Random;
import java.util.Scanner;
/**
* @Author: Cool_Wu
* @Date: 2020-12-01 23:39
*/
public class GuessNumberGame {
static int count = 0;
static int answer = new Random().nextInt(100);
public static void main(String[] args) throws Exception {
System.out.println("猜数字游戏开始,该数字是一个0~100之间的整数");
compareNum();
}
public static void compareNum() throws Exception {
if (count >= 10){
System.out.println("正确答案是:" + answer);
System.out.println("你太笨了,下次再来吧!");
return;
}
count++;
int n = receiveNum();
if (n < 0){
throw new Exception("您输入的数字不符合要求,请重新输入!");
}
if (n > 99){
throw new Exception("输入错误,请输入正确的数字!");
}
if (n < answer){
System.out.println("太小了,再大一点!");
compareNum();
}
if (n > answer){
System.out.println("太大了,再小一点!");
compareNum();
}
if (n == answer){
System.out.println("恭喜你,猜对了!");
}
}
public static int receiveNum() {
System.out.println("请输入您猜的数字:");
int n = new Scanner(System.in).nextInt();
return n;
}
}