需求分析:
1.要进行四则运算;
2.运算题目随机;
3.进行对错判断;
4.整数运算。
程序概要:
1.用JSP实现;
2.用户可选择题目数量;
3.答题页用表格列出;
4.包含用来填写答案的输入框;
5.答完后点击提交会直接显示相应题目的对错。
实现过程:
数据结构主要用到了数组
题目生成:
1 public String generateQuestion(int numOfOperand, int rangeMin, int rangMax, boolean isInt, 2 SupportedOperation[] operation, boolean bracket) { 3 String question = ""; //用来保存题目 4 int[] ioperands = null; //用来保存随机生成的操作数 5 double[] doperands = null; 6 SupportedOperation[] so = null; //用来保存操作符 7 if (numOfOperand < 2) { 8 System.out.println("操作数数量至少为2"); 9 return ""; 10 } 11 if (rangMax > 500) { 12 System.out.println("操作数数最大值不能超过500"); 13 return ""; 14 } //基础判断,看参数是否符合要求 15 if (isInt) { 16 ioperands = new int[numOfOperand]; 17 for (int i = 0; i < numOfOperand; i++) { 18 ioperands[i] = (int) (Math.random() * rangMax / 2 +1);//生成随机数并保存到数组中 19 20 } 21 question += ioperands[0]; //录入第一位操作数 22 //int sub = ioperands[0]; 23 so = new SupportedOperation[numOfOperand-1];//初始化操作符数组 24 for(int i = 0;i < operation.length;i++){ 25 if(operation[i] == SupportedOperation.ALL){ 26 operation = new SupportedOperation[4]; 27 operation[0] = SupportedOperation.ADD; 28 operation[1] = SupportedOperation.MINUS; 29 operation[2] = SupportedOperation.MULTIPLY; 30 operation[3] = SupportedOperation.DIVIDE; 31 32 } 33 } 34 int value = 0; //避免出现连续的除法运算 35 for(int j = 0;j<numOfOperand-1;j++){ 36 37 so[j] = operation[(int)(Math.random()*operation.length)]; 38 switch(so[j]){ //匹配操作符并写入算式 39 case ADD:question = ioperands[j+1]+"+"+question;break; 40 case MINUS:question = ioperands[j+1]+"-"+question;break; 41 case MULTIPLY:question = ioperands[j+1]+"*"+question;break; 42 case DIVIDE:{ //保证数能够整除 43 if(value < 1){ 44 ioperands[j+1] = ioperands[j+1]*ioperands[j]; 45 question =ioperands[j+1]+"/"+question; 46 47 value++; 48 } 49 else{ 50 j--; 51 } 52 }break; 53 default:System.out.println("操作符错误");break; 54 } 55 } 56 System.out.println(question); //以下部分主要用于测试 57 ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript"); 58 59 try { 60 Integer d = (Integer) se.eval(question); 61 System.out.println(d); 62 } catch (ScriptException e) { 63 e.printStackTrace(); 64 } 65 66 } else { 67 doperands = new double[numOfOperand]; 68 for (int i = 0; i < numOfOperand; i++) { 69 doperands[i] = Math.random() * rangMax / 2; 70 } 71 } 72 73 return question; 74 75 }
答案评定:
1 <script type="text/javascript"> 2 function compute() { 3 4 for (var i = 1; i <= <%=num%>; i++) { //对每一道题进行对错判断 5 var a = "" + eval(document.getElementById("q" + i).innerHTML); 6 var auser = document.getElementById("a" + i).value; 7 if (a == auser) { 8 document.getElementById("r" + i).innerHTML = "正确"; 9 } else { 10 document.getElementById("r" + i).innerHTML = "错误"; 11 } 12 } 13 14 } 15 </script>
程序运行结果
代码地址:https://coding.net/u/jx8zjs/p/paperOne/git
时间: 2024-10-22 05:00:47