軟體工程概論作業03--將隨機產生的運算式匯入資料庫

來源:互聯網
上載者:User

標籤:int   localhost   實驗   .exe   座標   []   throw   匯入資料   改進   

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Random;import java.util.Scanner;import java.util.Stack;public class Size {public static void main(String[] args) throws ClassNotFoundException, SQLException{Scanner sc = new Scanner (System.in);System.out.println("請選擇    1.整數運算    2.分數運算");int t = sc.nextInt();switch(t){case 1:{Integer(sc);break;}case 2:{fenshu(sc);}}}public static int simple(int a,int b)    //求最大公約數{int c=0;if(a>b){while(a!=b){c=a-b;if(b>=c){a=b;b=c;}if(c>b){a=c;}}return a;}else{while(a!=b){c=b-a;if(a>=c){b=a;a=c;}if(c>a){b=c;}}return a;}}public static int gongbei(int a,int b)      //求最小公倍數{int t=simple(a,b);return a*b/t;}public static String liangfenshujisuan(String a,String b,char c)          //兩個真分數的計算{int t=0;int t1=0,t2=0;int p1=0,p2=0;String s="";String d[]=a.split("\\/");String d1[]=b.split("\\/");int da[]=new int [d.length];int db[]=new int [d1.length];for(int i=0;i<d.length;i++){da[i]=Integer.parseInt(d[i]);}for(int i=0;i<d1.length;i++){db[i]=Integer.parseInt(d1[i]);}if(c==‘+‘){t=gongbei(da[1],db[1]);        //兩數分母同分t1=t/da[1];da[0]*=t1;                   //分子與分母相匹配t2=t/db[1];db[0]*=t2;p1=da[0]+db[0];s+=p1+"/"+t;}if(c==‘-‘){t=gongbei(da[1],db[1]);        //兩數分母同分t1=t/da[1];da[0]*=t1;                   //分子與分母相匹配t2=t/db[1];db[0]*=t2;p1=da[0]-db[0];if(p1<=0){return "error";}else{s+=p1+"/"+t;}}if(c==‘*‘){p1=da[0]*db[0];p2=da[1]*db[0];s+=p1+"/"+p2;}if(c==‘/‘){p1=da[0]*db[1];p2=da[1]*db[0];s+=p1+"/"+p2;}return s;}public static String fenshujisuan(String a)                       //分數運算式計算{Stack <String>num=new Stack <String>();Stack <String>fuhao=new Stack<String>();a+="#";fuhao.push("#");char ch;int i=0;int s=0;int y=0;ch=a.charAt(i);while(!(ch+"").equals("#")||(!(fuhao.peek().equals("#")))){if(ch==‘ ‘)          //如果ch=" ",則說明接下來是數字{String rn="";while(true){ch=a.charAt(++i);if(ch==‘ ‘){break;}rn+=ch;}if((i+1)<a.length()){ch=a.charAt(++i);}num.push(rn);}else           //遇到的是字元{char comp=youxian(fuhao.peek(),ch+"");  //比較兩個字元的優先順序if(comp==‘=‘)                          //說明遇到右括弧{                 fuhao.pop();if((i+1)<a.length()){ch=a.charAt(++i);}}else if(comp==‘>‘)                   //優先順序高,彈出兩個數和一個運算子,進行運算{String st1=num.pop();String st2=num.pop();String fuh1=fuhao.pop();char fuh2=fuh1.charAt(0);        //將String類型轉為char類型String sz=""; sz=liangfenshujisuan(st2,st1,fuh2);if(sz.equals("error"))                     //如果運算中有問題,就結束運算{return "error";}else{num.push(sz+"");             //將兩數結果壓入棧中}}else                                  //優先順序比較低,把運算子壓入棧中{fuhao.push(ch+"");if((i+1)<a.length()){ch=a.charAt(++i);}}}}return num.pop();}public static String fenshuchansheng(int n1,int t1)           //產生真分數的字串運算式  n1=2,3,4{Scanner sc=new Scanner(System.in);String s=" ";String a[]={"+","-","*","/"};int a1[]=new int [n1-1];int b[]=new int [2*n1];                  //產生的隨機數是運算元的2倍for(int i=0;i<2*n1;i=i+2){b[i]=(int)(Math.random()*t1);         //隨機產生第一個運算元的分子分母b[i+1]=(int)(Math.random()*t1);if((b[i]>=b[i+1])||(b[i+1]==0)||(b[i]==0))           //如果分子大於分母或分子、分母為0,重新賦值{i=i-2;}}for(int j=0;j<n1-1;j++){a1[j]=(int)(Math.random()*4);          //隨機產生運算子的位置}int i=0;for(int j=0;j<2*n1;j+=2){int t=simple(b[j],b[j+1]);       //第1,2個數是第一個運算元的分子分母,以此類推b[j] /=t;                       //化簡分子分母b[j+1] /=t;}for(int j=0;j<2*(n1-1);j+=2){s+=b[j]+"/"+b[j+1]+" "+a[a1[i]]+" ";i++;}s+=b[2*(n1-1)]+"/"+b[2*(n1-1)+1]+" ";return s;}public static String fenshuchanshengkuohao(int n1,int t1)     //產生帶括弧的真分數的字串運算式  n1=2,3,4{Scanner sc=new Scanner(System.in);String s=" ";String a[]={"+","-","*","/"};int a3[]=new int [n1];                   //記錄括弧產生的位置String a5[]=new String [n1];a3=chansheng(n1);int a1[]=new int [n1-1];int b[]=new int [2*n1];                  //產生的隨機數是運算元的2倍for(int i=0;i<2*n1;i=i+2){b[i]=(int)(Math.random()*t1);         //隨機產生第一個運算元的分子分母b[i+1]=(int)(Math.random()*t1);if((b[i]>=b[i+1])||(b[i+1]==0))           //如果分子大於分母或分母為0,重新賦值{i=i-2;}}for(int j=0;j<n1-1;j++){a1[j]=(int)(Math.random()*4);          //隨機產生運算子的位置}int i=0;for(int j=0;j<2*n1;j+=2)            //化簡真分數{int t=simple(b[j],b[j+1]);       //第1,2個數是第一個運算元的分子分母,以此類推b[j] /=t;                       //化簡分子分母b[j+1] /=t;}for(int j=0;j<2*(n1-1);j+=2){s+=b[j]+"/"+b[j+1]+" "+a[a1[i]]+" ";i++;}s+=b[2*(n1-1)]+"/"+b[2*(n1-1)+1]+" ";return s;}public static char youxian(String f,String s)                //計算兩個符號的優先順序{char a1[][]={{‘>‘,‘>‘,‘<‘,‘<‘,‘<‘,‘>‘,‘>‘},{‘>‘,‘>‘,‘<‘,‘<‘,‘<‘,‘>‘,‘>‘},{‘>‘,‘>‘,‘>‘,‘>‘,‘<‘,‘>‘,‘>‘},{‘>‘,‘>‘,‘>‘,‘>‘,‘<‘,‘>‘,‘>‘},{‘<‘,‘<‘,‘<‘,‘<‘,‘<‘,‘=‘,‘ ‘},{‘>‘,‘>‘,‘>‘,‘>‘,‘ ‘,‘>‘,‘>‘},{‘<‘,‘<‘,‘<‘,‘<‘,‘<‘,‘ ‘,‘=‘}};String a="+-*/()#";int a11=a.indexOf(f);   //找出運算子在表格中的行座標int a12=a.indexOf(s);   //找出運算子在表格中的行座標//System.out.println(f+"     "+s);return a1[a11][a12];}public static int [] chansheng(int num)                    //隨機產生括弧{int []b=new int[num];for(int i=0;i<b.length;i++){b[i]=0;}Random rd=new Random();for(int i=2;i<num;i++){for(int j=0;j<num-i+1;j++){int t=rd.nextInt(2);if(t==1){if(b[j]>=0&&b[j+i-1]<=0){int c=0;for(int k=j;k<j+i;k++){c+=b[k];}if(c==0){b[j]++;b[j+i-1]--;}}}}}return b;}public static String chanshengbiaodashi(int num,int t1)       //產生帶括弧的運算式{int a1[]=new int[num];int a2[]=new int[num-1];int a3[]=new int[num];String[]a5=new String[num];String[] a4={"+","-","*","/"};for(int i=0;i<num;i++){a1[i]=(int) (Math.random()*t1);}for(int i=0;i<num-1;i++){a2[i]=(int) (Math.random()*4);}a3=chansheng(num);for(int i=0;i<num;i++){a5[i]="";if(a3[i]<0){int c=0-a3[i];for(int j=0;j<c;j++){a5[i]+=")";}}else{for(int j=0;j<a3[i];j++){a5[i]+="(";}}}String t="";for(int i=0;i<num-1;i++){if(a3[i]>0){t+=a5[i]+" "+a1[i]+" "+a4[a2[i]];}else{t+=" "+a1[i]+" "+a5[i]+a4[a2[i]];}}if(a3[num-1]>0){t+=a5[num-1]+" "+a1[num-1]+" ";}else{t+=" "+a1[num-1]+" "+a5[num-1];}return t;}public static int[] tys(int a,int b,char c)   //兩個數的運算{int []a1=new int [2];            //a1[0]用來記錄兩數運算結果,a1[1]用來記錄兩數能否繼續算下去a1[0]=a1[1]=0;int d=0;if(c==‘+‘){d=a+b;}else if(c==‘-‘){if(a<b){a1[1]=1;}else{d=a-b;}}else if(c==‘*‘){d=a*b;}else{if((b==0)||(a%b!=0)||(a<b)){a1[1]=1;}elsed=a/b; }a1[0] = d;return a1;}public static String jisuan(String a)     //整數運算式的運算{Stack <String>num=new Stack <String>();Stack <String>fuhao=new Stack<String>();a+="#";fuhao.push("#");char ch;int i=0;int s=0;int y=0;ch=a.charAt(i);while(!(ch+"").equals("#") || !fuhao.peek().equals("#")){if(ch==‘ ‘)              //如果遇到字元為空白,說明遇到數字{String rn="";        //用來記錄資料while(true){ch=a.charAt(++i);if(ch==‘ ‘){break;}rn+=ch;}if((i+1)<a.length()){ch=a.charAt(++i);}num.push(rn);}else//遇到的是字元{char comp=youxian(fuhao.peek(),ch+"");  //比較兩個字元的優先順序if(comp==‘=‘)                          //說明遇到右括弧{                 fuhao.pop();if((i+1)<a.length()){ch=a.charAt(++i);}}else if(comp==‘>‘)                   //優先順序高,彈出兩個數和一個運算子,進行運算{String st1=num.pop();String st2=num.pop();int ai1 = Integer.parseInt(st1);int ai2 = Integer.parseInt(st2);String fuh1=fuhao.pop();char fuh2=fuh1.charAt(0);        //將String類型轉為char類型int []sz=new int[2]; sz=tys(ai2,ai1,fuh2);if(sz[1]==1)                     //如果運算中有問題,就結束運算{return "error";}else{num.push(sz[0]+"");          //將兩數結果壓入棧中}}else                                  //優先順序比較低,把運算子壓入棧中{fuhao.push(ch+"");if((i+1)<a.length()){ch=a.charAt(++i);}}}}return num.pop();}//整數運算public static void Integer(Scanner sc) throws ClassNotFoundException, SQLException{System.out.println("請選擇    1.不含括弧    2.含有括弧");int t = sc.nextInt();switch(t){case 1:{int numr=0;int numw=0;System.out.println("請輸入運算元的最大範圍:");int t1 = sc.nextInt();System.out.println("請輸入題目數量:");int n=sc.nextInt();String s1[]=new String [n];String str[] = new String [n];String str1[] = new String [n];String a[]={"+","-","*","/"};int b[][] = new int [n][];            //用二維表格儲存體運算元for(int i=0;i<n;i++)                 //產生運算式並輸出{str[i] = "第"+(i+1)+"題: ";str1[i] = " ";s1[i]="";int n1=(int) (Math.random()*3);            //隨機產生運算元的個數b[i]=new int[n1+2];   for(int j=0;j<n1+2;j++)    b[i][j]=(int) (Math.random()*t1);int d[] = new int [n1+1];                //儲存符號在a中的位置for(int j=0;j<n1+1;j++)                  //隨機產生數映射到運算子{d[j]=(int) (Math.random()*4);}for(int j=0;j<n1+1;j++)              //將運算式儲存到String類型的字串中{str[i]+=b[i][j]+" "+a[d[j]]+" ";str1[i] += b[i][j]+" "+a[d[j]]+" ";}str[i]+=b[i][n1+1]+" =";            //包含括弧,用於輸出str1[i] += b[i][n1+1]+" ";              //不包含括弧,方便堆棧過程的計算boolean flag=true; for(int j=i-1;j>=0;j--){if(str1[i]==str1[j])            //判斷是否重複{flag=false;break;}else if((n1==0)&&((d[0]==0)||(d[0]==2))&&           //乘法或加法交換同樣重複 ((b[i][0]==b[j][1])&&(b[i][1]==b[j][0]))){flag = false;break;}}for(int z=0;z<n1+1;z++)        //判斷有除法時,後邊的運算元是否為0{if(d[z]==3&&b[i][z+1]==0){flag=false;break;}}if( flag==false){i--;}else{String s =jisuan(str1[i]);    s1[i]+=jisuan(str1[i]);if(s.equals("error")){i--;}else{System.out.print(str[i]);String q=sc.next();if(q.equals(s)){System.out.println("恭喜你,回答正確!");numr++;}else{System.out.println("很遺憾,回答錯誤!  正確結果為:"+s);numw++;}}}}lianjiezhengshu(str,s1);System.out.println("一共"+n+"道題,答對"+numr+"道,錯誤"+numw+"道,繼續努力!");break;}case 2:{int numr=0;int numw=0;  System.out.println("請輸入運算元的最大範圍:");int t1 = sc.nextInt();System.out.println("請輸入題目數量:");int n=sc.nextInt();String str[] = new String [n];    String str1[] = new String [n];String s1[]=new String [n];for(int i=0;i<n;i++){str[i]="";str1[i]="第"+(i+1)+"題: ";s1[i]="";int n1=(int) (Math.random()*3);            //隨機產生運算元的個數str[i]+=chanshengbiaodashi(n1+2,t1);str1[i]+=str[i]+" =";String s = jisuan(str[i]);s1[i]+=jisuan(str[i]);if(s.equals("error")){i--;}else{System.out.print(str1[i]);String q=sc.next();if(q.equals(s)){System.out.println("恭喜你,回答正確!");numr++;}else{System.out.println("很遺憾,回答錯誤!  正確結果為:"+s);numw++;}}}lianjiezhengshu(str1,s1);System.out.println("一共"+n+"道題,答對"+numr+"道,錯誤"+numw+"道,繼續努力!");break;}}}//分數運算public static void fenshu(Scanner sc) throws ClassNotFoundException, SQLException{System.out.println("請輸入題目數量:");int n=sc.nextInt();System.out.println("請輸入運算元範圍:");int t1=sc.nextInt();String str[] = new String [n];String str1[]= new String [n];String s[]=new String[n];String s1[]=new String [n];for(int i=0;i<n;i++){int n1=(int) (Math.random()*3);str1[i]="第"+(i+1)+"道題目:";str1[i]+=fenshuchansheng(n1+2,t1);str[i]=fenshuchansheng(n1+2,t1);s[i]=fenshujisuan(str[i]);s1[i]="";int z=1;for(int j=i-1;j>=0;j--){if(str[i].equals(str[j])){z=0;break;}//else if()}if((z==0)||(s[i].equals("error"))){i--;}else{String b1[] =new String [2];                //對運算結果進行化簡    int b[]=new int [2];b1=s[i].split("\\/");b[0]=Integer.parseInt(b1[0]);b[1]=Integer.parseInt(b1[1]);int t=simple(b[0],b[1]);b[0] /=t;b[1] /=t;int a=(int)(b[0]/b[1]);int c=b[0]%b[1];if(b[0]>b[1])              //判斷結果格式{if(b[0]%b[1]==0){s1[i]+=a;System.out.println("第"+(i+1)+"道題目:"+str[i]+" ="+a);}else{s1[i]+=a+"‘"+c+"/"+b[1];System.out.println("第"+(i+1)+"道題目:"+str[i]+" ="+s1[i]);}}if(b[1]>b[0]){s1[i]+=b[0]+"/"+b[1];System.out.println("第"+(i+1)+"道題目:"+str[i]+" ="+s1[i]);}else if(b[0]==b[1]){s1[i]+="1";System.out.println("第"+(i+1)+"道題目:"+str[i]+" ="+s1[i]);}}}lianjiefenshu(str1,s1);             //串連資料庫,將運算式和結果匯入資料庫System.out.println("匯入成功!");}    //分數串連資料庫public static void lianjiefenshu(String a[],String b[]) throws ClassNotFoundException, SQLException    {Connection conn = null;PreparedStatement pstmt = null;String driverName = "com.mysql.jdbc.Driver";String userName = "root";String userPwd = "123456789";String ur11 = "jdbc:mysql://localhost:3306/size03";String ur12 = "?user=" + userName + "&password=" + userPwd;String ur13 = "&useUnicode=true&characterEncoding=UTF-8";String ur1 = ur11 + ur12 + ur13;Class.forName(driverName);conn = DriverManager.getConnection(ur1);String sql = "insert into text03fenshu(運算式,結果) values(?,?)";pstmt = conn.prepareStatement(sql);for(int i=0;i<a.length;i++){pstmt.setString(1,a[i] );    pstmt.setString(2, b[i]);    pstmt.executeUpdate();}if(pstmt !=null){ pstmt.close();}if(conn!=null){ conn.close();}       }//整數串連資料庫public static void lianjiezhengshu(String a[],String b[]) throws ClassNotFoundException, SQLException    {Connection conn = null;PreparedStatement pstmt = null;String driverName = "com.mysql.jdbc.Driver";String userName = "root";String userPwd = "123456789";String ur11 = "jdbc:mysql://localhost:3306/size03";String ur12 = "?user=" + userName + "&password=" + userPwd;String ur13 = "&useUnicode=true&characterEncoding=UTF-8";String ur1 = ur11 + ur12 + ur13;Class.forName(driverName);conn = DriverManager.getConnection(ur1);String sql = "insert into text03zhengshu(運算式,結果) values(?,?)";pstmt = conn.prepareStatement(sql);for(int i=0;i<a.length;i++){pstmt.setString(1,a[i] );    pstmt.setString(2, b[i]);    pstmt.executeUpdate();}if(pstmt !=null){ pstmt.close();}if(conn!=null){ conn.close();}       }}

  

設計思想:

   這次的實驗較上次的改進有,整數運算可以隨機產生不超過四個的運算元,可以隨機產生括弧;

分數部分,可以隨機產生不超過四個的運算元,對於多於兩個運算元的運算式,利用堆棧的方式進行計算,

首先將String類型的運算式利用空格將數字與運算子分開,將數字強制轉換為int類型,進行計算。

最後將運算式和結果都匯入資料庫,調用資料庫,與輸入的值比較,查看結果是否匹配,最後統計正確和錯誤的個數。

 

 運行

                                             

 

                         

                   

 

軟體工程概論作業03--將隨機產生的運算式匯入資料庫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.