採用面向對象程序設計的方式,設計小學數學考試系統的有關類java
(題目數量,題目類型(四則運算),題目內容都是隨機產生),提供答題及自動評分的功能。dom
思路:將每一道數學題抽象爲一個對象,所以能夠寫出一個類來實現數學題。this
而後再Test中再用隨機數來肯定題目的數量,至於判分功能,再數學類中定義一個static類型的數據,這個static數據是全部數學類的對象所共享的,因此能夠用來作計數器。spa
package pro3; import java.math.BigDecimal; import java.util.*; public class Math01 { public static void main(String[] args) { Test t1=new Test(); t1.print(); } } class Test{ private int key; private Math_test m[]; public Test(){ key=random(10); m=new Math_test[key]; for(int i=0;i<key;i++){ m[i]=new Math_test(); } } private int random(int n){ Random random=new Random(); int i=random.nextInt(n)+1; return i; } public void print(){ for(int i=0;i<key;i++){ m[i].test(); } System.out.println("最終得分"+Math_test.count+"0分"); } } class Math_test{ public static int count; private int num01; private int num02; double user_ans,ans; int key; static{ count=0; } public Math_test(){ this.num01=random(100); this.num02=random(100); } private int random(int n){ Random random=new Random(); int i=random.nextInt(n)+1; return i; } private char operator(){ key=random(4); switch(key){ case 1:{return '+';} case 2:{return '-';} case 3:{return '*';} case 4:{return '/';} } return ' '; } private void user_calcu(){ Scanner sc=new Scanner(System.in); System.out.print("請計算:"+this.num01+operator()+this.num02+"="); user_ans=sc.nextDouble(); } public void judge(){ float div=0; float div1=0; {//把float型的結果 四捨五入 div=(float)this.num01/this.num02; BigDecimal b=new BigDecimal(div); BigDecimal b1=b.setScale(2, 4); div1=b1.floatValue(); } if(key==1&&user_ans==(this.num01+this.num02)){ System.out.println("\t正確"); count++; }else if(key==2&&user_ans==(this.num01-this.num02)){ System.out.println("\t正確"); count++; }else if(key==3&&user_ans==(this.num01*this.num02)){ System.out.println("\t正確"); count++; }else if(key==4&&user_ans==div1){ System.out.println("\t正確"); count++; }else{ System.out.println("\t錯誤"); } } public void test(){ user_calcu(); judge(); } }