Introduction to Software engineering operations 03--importing randomly generated expressions into a database

Source: Internet
Author: User

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 ("Please select 1. Integer operation 2. Fractional operation"); int t = sc.nextint (); switch (t) {case 1:{integer (SC); Case 2:{fenshu (SC);}}} public static int simple (int a,int b)//Beg greatest common Divisor {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)//request least common multiple {int t=simple (a, b); return a*b/t;} public static string Liangfenshujisuan (String a,string b,char C)//Two true fraction calculation {int T=0;int t1=0,t2=0;int p1=0,p2=0;s Tring 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]);                   The denominator of two numbers t1=t/da[1];d a[0]*=t1; Numerator and denominator match t2=t/db[1];d b[0]*=t2;p1=da[0]+db[0];s+=p1+ "/" +T;}        if (c== '-') {T=gongbei (da[1],db[1]);                   The denominator of two numbers t1=t/da[1];d a[0]*=t1; Numerator and denominator match t2=t/db[1];d b[0]*=t2;p1=da[0]-db[0];if (p1<=0) {return "error";} else{s+=p1+ "/" +T;}} if (c== ' * ') {p1=da[0]*db[0];p 2=da[1]*db[0];s+=p1+ "/" +P2;} if (c== '/') {p1=da[0]*db[1];p 2=da[1]*db[0];s+=p1+ "/" +P2;} return s;} public static string Fenshujisuan (String a)//fractional expression evaluates {stack <string>num=new stack &LT;STRING&G t; (); 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== ')//If Ch= "", then the number {String rn= "" is followed, while (true) {Ch=a.charat (++i); if (ch== ") {bReak;} Rn+=ch;} if ((i+1) <a.length ()) {Ch=a.charat (++i);} Num.push (RN);}  else//encountered is the character {char Comp=youxian (Fuhao.peek (), ch+ ""); Compare two-character priority if (comp== ' = ')//description encounters closing parenthesis {fuhao.pop (); if ((i+1) <a.length ()) {Ch=a.cha RAt (++i);}} else if (comp== ' > ')//priority high, two numbers and an operator are popped, operation {String st1=num.pop (); String St2=num.pop ();        String Fuh1=fuhao.pop (); char fuh2=fuh1.charat (0); Convert string type to char type string sz= ""; Sz=liangfenshujisuan (ST2,ST1,FUH2); if (Sz.equals ("error")//if there is a problem in the operation, end the operation {return "error";}             Else{num.push (sz+ ""); Press the two number result into the stack}}else//Priority Low, put the operator into the stack {Fuhao.push (ch+ ""); if ((i+1) <a.length ()) {Ch=a.charat (++i);}}} return Num.pop ();} public static string Fenshuchansheng (int n1,int t1)//generating a true fraction of strings expression N1=2,3,4{scanner sc=new Scanner (system.in); S Tring s= "";                  String a[]={"+", "-", "*", "/"};int a1[]=new int [n1-1];int b[]=new int [2*n1]; The generated random number is 2 of the operandtimes for (int i=0;i<2*n1;i=i+2) {b[i]= (int) (Math.random () *t1); The numerator denominator b[i+1]= (int) (Math.random () *t1) of the first operand is randomly generated; if (b[i]>=b[i+1]) | | (b[i+1]==0) | |           (b[i]==0)) If the numerator is greater than the denominator or numerator, the denominator is 0, the value is re-assigned {i=i-2;}}          for (int j=0;j<n1-1;j++) {a1[j]= (int) (Math.random ());       The position of the randomly generated operator}int i=0;for (int j=0;j<2*n1;j+=2) {int t=simple (b[j],b[j+1]);                       1th, 2 numbers are the numerator denominator of the first operand, and so on B[j]/=t; degeneracy numerator denominator 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)//string expression that produces a true fraction of parentheses N1=2,3,4{scanner sc=new Scanner (system.i n); String s= "";                   String a[]={"+", "-", "*", "/"};int a3[]=new int [N1];                  Record the position where the parentheses are generated by string a5[]=new string [N1];a3=chansheng (n1); int a1[]=new int [n1-1];int b[]=new int [2*n1];         The generated random number is twice times the number of operands for (int i=0;i<2*n1;i=i+2) {b[i]= (int) (Math.random () *t1); The numerator denominator b[i+1]= (int) of the first operand is randomly generated (math.randoM () *t1); if ((b[i]>=b[i+1)) | |           (b[i+1]==0)) If the numerator is greater than the denominator or denominator is 0, the value is re-assigned {i=i-2;}}          for (int j=0;j<n1-1;j++) {a1[j]= (int) (Math.random ());       The position of the randomly generated operator}int i=0;for (int j=0;j<2*n1;j+=2)//simplifying the true fraction {int t=simple (b[j],b[j+1]);                       1th, 2 numbers are the numerator denominator of the first operand, and so on B[j]/=t; degeneracy numerator denominator 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)//calculates the priority of two symbols {char a1[][]={{' > ', ' > ', ' < ', ' < ', ' < ' , ' > ', ' > '},{' > ', ' > ', ' < ', ' < ', ' < ', ' > ', ' > '},{' > ', ' > ', ' > ', ' > ', ' < ', ' > ', ' > '},{' > ', ' > ', ' > ', ' > ', ' < ', ' > ', ' > '},{' < ', ' < ', ' < ', ' < ', ' < ', ' = ', '},{' > ' , ' > ', ' > ', ' > ', ' ', ' > ', ' > '},{' < ', ' < ', ' < ', ' < ', ' < ', ' ', ' = '};   String a= "+-*/() #"; int a11=a.indexof (f);   Find the operator's row coordinates in the table int a12=a.indexof (s);   Find the operator's row coordinates in the table//system.out.println (f+ "  "+s"); return a1[a11][a12];} public static int [] Chansheng (int num)//randomly generates parentheses {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)//produce parenthesized expression {int a1[]=new int[num];int a2[]=new int[num-1];in T 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 ());} 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)//two number of operations {int []a1=new int [2]; A1[0] is used to record the results of a two-digit operation, a1[1] is used to record whether the two numbers can continue to be counted 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&LT;B)) {a1[1]=1;} elsed=a/b; }a1[0] = D;return A1;} public static string Jisuan (String a)//integer expression operation {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== ')//If the character is null, the description encounters the number {String rn= ""; Used to record data while (true) {Ch=a.charat (++i); if (ch== ") {break;} Rn+=ch;} if ((i+1) <a.length ()) {Ch=a.charat (++i);} Num.push (RN);}  Else//encountered is the character {char Comp=youxian (Fuhao.peek (), ch+ "");        Compares the two-character priority if (comp== ' = ')//description encounters a closing parenthesis {         Fuhao.pop (); if ((i+1) <a.length ()) {Ch=a.charat (++i);}} else if (comp== ' > ')//priority high, two numbers and an operator are popped, operation {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); Convert string type to char type int []sz=new int[2]; Sz=tys (AI2,AI1,FUH2); if (sz[1]==1)//If there is a problem in the operation, end the operation {return "error";}          Else{num.push (sz[0]+ ""); Press the two number result into the stack}}else//Priority Low, put the operator into the stack {Fuhao.push (ch+ ""); if ((i+1) <a.length ()) {Ch=a.charat (++i);}}} return Num.pop ();} Integer operation public static void Integer (Scanner sc) throws ClassNotFoundException, Sqlexception{system.out.println ("Please select 1. Not included No. 2. With parentheses "); int t = sc.nextint (); switch (t) {case 1:{int numr=0;int numw=0; System.out.println ("Please enter the maximum range of operands:"); int t1 = Sc.nextint (); System.out.println ("Please enter the number of questions:"); int n=sc.nextint (); string S1[]=new string [n]; String str[] = new string [n]; String str1[] = new string [n]; Stringa[]={"+", "-", "*", "/"};int b[][] = new int [n][];  Store operand for (int i=0;i<n;i++)//build expression with two-dimensional table and output {str[i] = "First" + (i+1) + "title:"; Str1[i] = ""; s1[i]= ""; int n1= (int)            (Math.random ());   Number of randomly generated operands 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]; Stores the position of the symbol in a for (int j=0;j<n1+1;j++)//random generation number mapped to operator {d[j]= (int) (Math.random ());} for (int j=0;j<n1+1;j++)//To store expressions in string-type strings {str[i]+=b[i][j]+ "" +a[d[j]]+ ""; Str1[i] + = b[i][j]+ "" +a[d[ J]]+ "";}            str[i]+=b[i][n1+1]+ "=";              Contains parentheses for output STR1[I] + = b[i][n1+1]+ ""; Does not include parentheses to facilitate the calculation of the stack process Boolean flag=true; for (int j=i-1;j>=0;j--) {if (Str1[i]==str1[j])//To determine whether to repeat {flag=false;break;} else if ((n1==0) && ((d[0]==0) | | (d[0]==2)) &&//multiplication or addition exchange repeats ((B[i][0]==b[j][1]) && (b[i][1]==b[j][0])) {flag = False;break;}} for (int z=0;z<n1+1;z++)//To determine if there is division, the number of operands behind is 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 ("Congratulations, answer right!"); numr++;}  Else{system.out.println ("Very sorry to answer the wrong!") The correct result is: "+s); numw++;}}} Lianjiezhengshu (STR,S1); System.out.println ("A total of" +n+ "problem, correct" +numr+ "road, The Wrong" +numw+ "road, continue to work! "); break;}  Case 2:{int Numr=0;int numw=0; System.out.println ("Please enter the maximum range of operands:"); int t1 = Sc.nextint (); System.out.println ("Please enter the number of questions:"); 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) + "title:"; s1[i]= ""; int n1= (int) (            Math.random ()); Number of randomly generated operands 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 ("Congratulations, answer right!"); Numr++;}  Else{system.out.println ("Very sorry to answer the wrong!") The correct result is: "+s); numw++;}}} Lianjiezhengshu (STR1,S1); System.out.println ("A total of" +n+ "problem, correct" +numr+ "road, The Wrong" +numw+ "road, continue to work! "); break;}} Fractional operation public static void Fenshu (Scanner SC) throws ClassNotFoundException, Sqlexception{system.out.println ("Please enter the number of questions:" ); int N=sc.nextint (); System.out.println ("Please enter operand range:"); 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 () *), str1[i]= "+ (i+1) +" road title: "; 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]; Simplification of the result of the operation 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])//judgment result format {if (b[0]%b[1]==0) {s1[i]+=a; System.out.println ("i+1" + "road title:" +str[i]+ "=" +a ");} else{s1[i]+=a+ "'" +c+ "/" +b[1 "; System.out.println ("+ (i+1) +" Tao Title: "+str[i]+" = "+s1[i]");}} if (B[1]>b[0]) {s1[i]+=b[0]+ "/" +b[1]; System.out.println ("+ (i+1) +" Tao Title: "+str[i]+" = "+s1[i]");} else if (b[0]==b[1]) {s1[i]+= "1"; System.out.println ("+ (i+1) +" Tao Title: "+str[i]+" = "+s1[i]");}}}             Lianjiefenshu (STR1,S1); Connect the database, import expressions and results into the database System.out.println ("Import succeeded!    ");} Fractional connection database public static void Lianjiefenshu (String a[],string b[]) throws ClassNotFoundException, SQLException {connectio n 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 (expression, result) 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 ();} }//Integer connection database public static void Lianjiezhengshu (String a[],string b[]) throws ClassNotFoundException, SQLException {Connec tion 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 (expression, result) 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 ();} }}

  

Design ideas:

This experiment compared with the previous improvement has, the integer operation can randomly produce no more than four operands, you can randomly generate parentheses;

Fractional part, can randomly produce no more than four operands, for more than two operands of the expression, the use of the stack to calculate the way,

A string type expression is first separated by a space from the operator, the number is cast to the int type, and the calculation is performed.

Finally, the expressions and results are imported into the database, the database is called, compared with the values entered, the results are checked to see if they match, and the number of errors is finally counted.

Run

Introduction to Software engineering operations 03--importing randomly generated expressions into a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.