完成将生成的加减乘除算术添加到数据库中,并且将算数从数据库取出来
运行结果
源代码
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Random; import java.util.Scanner; import util.DBUtil; public class Dao { static int num; static String []s=new String [100]; public static void main(String args[]) throws Exception{ menu(); Scanner sc=new Scanner(System.in); int choose=sc.nextInt(); if(choose==1) { setQustion(); }else if(choose==2) { getQuestion(); } sc.close(); } //创建运算式题目 public static String creat(){ int x,y,z; Random rand=new Random(); x= rand.nextInt(100)+1; y=rand.nextInt(100)+1; z=rand.nextInt(4)+1; String str=""; if (z==1){ num=x+y; str=x+"+"+y; return str; }else if(z==2){ num=x-y; str=x+"-"+y; }else if(z==3){ num=x*y; str=x+"*"+y; }else if(z==4){ num=x/y; str=x+"/"+y; } return str; } //判断算式是否重复,包括反向的重复 public static boolean test(String w,int i){ String w1=new StringBuffer(w).reverse().toString(); for (int j=0;j<i;j++){ if (w.equals(s[j])&&w1.equals(s[j])){ return true; } } return false; } public static void menu() { System.out.println("请选择你要进行的操作"); System.out.println("1.生成题目并将题目存到数据库中"); System.out.println("2.从数据库中读取数据"); System.out.print("请输入您的操作(1/2)"); } public static void getQuestion()throws Exception { Connection connection =DBUtil.getConnection(); String sql="select question from que;"; PreparedStatement pstm=null; pstm = connection.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while(rs.next()) { String question=rs.getString("question"); System.out.println(question); } System.out.println("是否选择获取答案(1是/2否)"); Scanner sc=new Scanner(System.in); int flag=sc.nextInt(); if(flag==1) { getDaan(); } sc.close(); DBUtil.close(connection); DBUtil.close(pstm); } public static void getDaan()throws Exception{ Connection connection =DBUtil.getConnection(); PreparedStatement pstm=null; String sql="select daan from que;"; pstm=connection.prepareStatement(sql); ResultSet rs=pstm.executeQuery(); while(rs.next()) { String n=rs.getString("daan"); System.out.println(n); } DBUtil.close(connection); DBUtil.close(pstm); } public static void setQustion() throws Exception { //连接数据库 Connection connection= DBUtil.getConnection(); Scanner sc=new Scanner(System.in); System.out.println("请输入存储的题目个数:"); int n= sc.nextInt(); String sql=null; PreparedStatement pstmt = null; try { for (int i=0;i<n;i++){ String question=creat(); if (test(question,i)){ continue; //如果重复就跳过循环,不进行存入 } sql="insert into que values(?,?)"; pstmt =connection.prepareStatement(sql); pstmt.setString(1, question); pstmt.setString(2, Double.toString(num)); pstmt.executeUpdate(); System.out.println(question+" "+num); sql=""; } }finally { DBUtil.close(connection); DBUtil.close(pstmt); sc.close(); } } }
标签:11,27,java,String,int,每日,static,str,import From: https://www.cnblogs.com/cinan/p/17860105.html