/** 随机加减乘除运算器,要求如下:程序依次出 10 道题目,由用户输入题目的答案。用户 每答完一道题,由系统提示结果:答错了或者答对了。10 道题目答完之后,系统计算得分 并输出。如果用户希望提前结束,则可以输入-1提前退出。 ------------------------------------- */ public class MathTest { /*定义静态常量 为下面的switch做准备*/ public static final int ADD = 0; public static final int SUB = 1; public static final int MULTI = 2; public static final int DIV = 3; //除法不准确,想准确需要都换成double类型 public static void main(String[] args) { System.out.println("随机加减乘除运算器,程序启动"); operation(); } public static void operation() { Scanner scan = new Scanner(System.in); Random random = new Random(); int score = 0; for(int i =0; i<10; i++){ int num1 = random.nextInt(10); int num2 = random.nextInt(10)+1; //加1避免除数是0的情况 int sum = 0; int answer ; int type = random.nextInt(4); //随机生成加减乘除4种选择 switch(type){ case ADD: sum = num1+num2; System.out.println("["+(i+1)+"] "+num1+"+"+num2+" = ?"); break; case SUB: sum = num1-num2; System.out.println("["+(i+1)+"] "+num1+"-"+num2+" = ?"); break; case MULTI: sum = num1*num2; System.out.println("["+(i+1)+"] "+num1+"*"+num2+" = ?"); break; case DIV: sum = num1/num2; System.out.println("["+(i+1)+"] "+num1+"/"+num2+" = ?"); break; } System.out.println("请输入答案:"); answer = scan.nextInt(); if(answer == sum){ System.out.println("答对,得分:"+(score+=10)); }else if(answer == -1){ System.out.println("退出游戏"); break; }else{ System.out.println("答错,下一题"); } } } }
原文:http://www.cnblogs.com/zyjcxc/p/5449817.html