package com.模拟练习题一;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 1.键盘输入10个数,放到数组中
    a.    去除该数组中大于10的数
    b.    将该数组中的数字写入到本地文件number.txt中
    
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //键盘输入10个数数组
        int[] arr = getArr();
        //去除大于10的
        int[] arr1 = remove(arr);
        //写入
        BufferedWriter bw = new BufferedWriter(new FileWriter("number.txt"));
        for (int i : arr1) {
            bw.write(i+" ");
        }
        bw.close();
    }

    private static int[] remove(int[] arr) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]>10){
                list.add(arr[i]);
            }
        }
        int[] arr1 = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr1[i] = list.get(i);
        }
        return arr1;
    }

    private static int[] getArr() {
        System.out.println("请输入10个整数:");
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] =sc.nextInt();
        }
        return arr;
    }
}
package com.模拟练习题一;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 2.map中有如下数据(电话号=套餐价格)
    [13265477888=168,15241698745=11,13699989898=20,1898686666=120]
    在ip为127.0.0.1数据库名为stdb,连接数据库的用户名和密码为:admin和123456中有一个numinfo表相关字段为(id,iphonenum,tomoney)(15分)
    (1)将map中的手机号码取出来打印到控制台上(3分)
    (2)判断map中所有的手机号在numinfo表中是否存在存在则输出"该主机已登录"如果不存在将该号码及对应的套餐价格存入到numinfo表中.(12分)
    (map中的数据不需要修改)
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) throws Exception {
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("13265477888", 168);
        map.put("15241698745", 11);
        map.put("13699989898", 20);
        map.put("18986886666", 120);
        System.out.println(map);
        
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mybase", "root", "123456");
        PreparedStatement pstmt=null;
        ResultSet rs =null;
        for(String phone : map.keySet()){
            Integer values = map.get(phone);
            String sql = "select * from numinfo where iphonenum=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, phone);
            rs = pstmt.executeQuery();
            if(rs.next()){
                System.out.println("以登录");
            }else{
                String sql1 = "insert into numinfo(iphonenum,tomoney) values (?,?)";
                pstmt = con.prepareStatement(sql1);
                pstmt.setString(1, phone);
                pstmt.setInt(2, values);
                int row = pstmt.executeUpdate();
                if(row!=0){                    
                    System.out.println("注册成功");
                }
            }
        }
        con.close();
        rs.close();
        pstmt.close();
    }
}
package com.模拟练习题二;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1.产生10个1-100的随机数,并放到一个数组中
    (1)把数组中大于等于10的数字放到一个list集合中,并打印到控制台。
    (2)把数组中小于10的数字放到一个map集合中,并打印到控制台。
    (3)把数组中的数字放到当前文件夹的number.txt文件中
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        int[] arr = getRomdon();
        List<Integer> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        BufferedWriter bw = new BufferedWriter(new FileWriter("number.txt"));
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] >= 10){
                list.add(arr[i]);
            }else{
                map.put(i, arr[i]);
            }
            bw.write(arr[i]+" ");
        }
        System.out.println(list);
        System.out.println(map);
        bw.close();
    }

    private static int[] getRomdon() {
        // TODO Auto-generated method stub
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            int num = (int) (Math.random()*100+1);
            arr[i]=num;
        }
        return arr;
    }    
}
package com.模拟练习题二;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 2.数据库题:
    用jdbc链接数据库stu,该数据中有一个表为student,
    表中数据如下:
     id       name    sex     score
     1       李少荣    女      80
     2       邵凯      男      75
     3       周强      男      95
     4       王晓婷    女      55
     5       张秀花    女      68
     6       顾会      女      50
     7       赵天一    男      32
    (1)查找60分以上的学生信息
    (2)将男生且名字是两个数的成绩改成100。
 *
 */
public class Demo02 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase","root","123456");
//        query(con);
        update(con);
    }

    private static void update(Connection con) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "update  student set score=100 where name like'__' and sex='男'";
        PreparedStatement pstmt = con.prepareStatement(sql);
        int row = pstmt.executeUpdate(sql);
        System.out.println(row);
    }

    private static void query(Connection con) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "select * from student where score>60";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int count = rs.getMetaData().getColumnCount();
        while(rs.next()){
            for (int i = 1; i <= count; i++) {
                System.out.print(rs.getString(i));
                if(i<count){
                    System.out.print(",");
                }
            }
            System.out.println();
        }
        rs.close();
        pstmt.close();
        con.close();
    }
}
package com.模拟练习题三;

import java.util.Scanner;

/**
 * 1.设计一个程序,键盘输入月份,控制条输出季节.3,4,5春季/6,7,8夏季/9,10,11秋季/12,1,2冬季
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        System.out.println("请输入月份");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        if(num>=1 && num<=12){
            if(num>=3 && num<=5){
                System.out.println("春季");
            }
            if(num>=6 && num<=8){
                System.out.println("夏季");
            }
            if(num>=9 && num<=11){
                System.out.println("秋季");
            }
            if(num==12 || num<=2){
                System.out.println("冬季");
            }
        }else
            System.out.println("你输入的月份不存在");
    }
}
package com.模拟练习题三;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 2.向list集合添加姓名{张三,李四,王五,二丫,钱六,孙七},将二丫替换为王小丫,写入到"D:\\stuinfo.txt"
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) throws IOException {
        List<String> list  = new ArrayList<>();
        Collections.addAll(list, "张三","李四","王五","二丫","钱六","孙七");
        BufferedWriter bw = new BufferedWriter(new FileWriter("stuinfo.txt"));
        for (int i = 0; i < list.size(); i++) {
            //判断集合中的元素有没有等于"二丫"的改成王二牙  
            if(list.get(i).equals("二丫")){
                list.set(i, "王二丫");                
                //改过后写入文件中
                bw.write(list.get(i)+" ");
                //跳出本次循环,不然会被写入两次,if外还在循环写入
                continue;
            }
            bw.write(list.get(i)+" ");
        }
        //释放资源
        bw.close();
    }
    
}
package com.模拟练习题三;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 3.一个数据库stu,用户名为admin 密码为123456 已存在一个表中有五个学生的信息,姓名,性别,年龄,分数.
    id       name      sex     score
     1       李少荣    女      80
     2       邵凯      男      75
     3       周强      男      95
     4       王晓婷    女      55
     5       张秀花    女      68
     6       顾会      女      50
     7       赵天一    男      32
    (1)查询女性,成绩80以上
    (2)将姓张的男同学的的成绩改为100
    (3)查询年龄大于20的女性,显示姓名,性别,年龄
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws Exception {
        //加载驱动类
        Class.forName("com.mysql.jdbc.Driver");
        //接连数据库
        Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase", "root", "123456");
//        query(con);
//        update(con);
        queryse(con);
    }

    private static void queryse(Connection con) throws SQLException {
        String sql = "select * from student where score>50 and sex='女'";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            System.out.println(rs.getString("name")+","+rs.getString("sex")+","+rs.getString("score"));
        }
    }

    private static void update(Connection con) throws SQLException {
        // TODO Auto-generated method stub
        String sql ="update student set score=100 where name like'赵%' and sex='男'";
        PreparedStatement pstmt  = con.prepareStatement(sql);
        int row = pstmt.executeUpdate();
        System.out.println(row);
    }

    private static void query(Connection con) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "select * from student where score>80 and sex='女'";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int count = rs.getMetaData().getColumnCount();
        while(rs.next()){
            for (int i = 1; i <= count; i++) {
                System.out.print(rs.getString(i));
                if(i<count){
                    System.out.print(",");
                }
            }
            System.out.println();
        }
        rs.close();
        pstmt.close();
        con.close();
    }
}
package com.模拟练习题四;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/** 
 *2.从控制台获取输入的文件目录然后将指定目录下的.java文件复制到D:/java文件夹中
 * @author Administrator
 */
public class Demo02 {
    public static void main(String[] args) throws IOException {
        File file = getFile();
        File dest = new File("D:\\java");
        if(!dest.exists()){
            dest.mkdirs();
        }
        copy(file,dest);
    }

    private static void copy(File file, File dest) throws IOException {
        // TODO Auto-generated method stub
        File[] files = file.listFiles();
        if(files!=null){
            for (File file2 : files) {
                //判断是否是文件   在判断段结尾是否是.java
                if(file2.isFile() && file2.getName().toLowerCase().endsWith(".java")){
                    BufferedInputStream br = new BufferedInputStream(new FileInputStream(file2));
                    BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(new File(dest,file2.getName())));
                    byte[] by = new byte[1024];
                    int len = 0;
                    while((len=br.read())!=-1){
                        bw.write(by, 0, len);
                    }
                    br.close();
                    bw.close();
                }else if(file2.isDirectory()){
                    copy(file2, dest);
                }
            }
        }
    }

    private static File getFile() {
        // TODO Auto-generated method stub
        System.out.println("请输入一个文件夹路径");
        Scanner sc = new Scanner(System.in);
        String str =sc.nextLine();
        File file = new File(str);
        while(true){        
            if(!file.exists()){
                System.out.println("你输入的文件夹路径不存在,请重新输入");
            }else if(file.isFile()){
                System.out.println("你输入的是文件路径,请重新输入");
            }else{            
                return file;
            }
        }
    }
}
package com.模拟练习题五;
/**
 * 1.写一个卖票的程序,
     1.写一个类,该类实现了Runnable接口.有一个私有类型的int作为参数tickets.
       票的总数为100,完成run方法,输出结果的格式如下:
       当前窗口为:窗口a,剩余票数为19,其中窗口a为线程的名字
     2.开启四个卖票窗口(开始四个线程),同时执行卖票的程序
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        Tick t = new Tick();
        new Thread(t,"线程A").start();
        new Thread(t,"线程B").start();
        new Thread(t,"线程C").start();
        new Thread(t,"线程D").start();
    }
}
class Tick implements Runnable{
    static int tickers =100;
    @Override
    public void run() {
        while(true){
            synchronized (this) {
                String name = Thread.currentThread().getName();
                //如果票数小于0  4条线程依次结束
                if(tickers<=0){
                    return;
                }
                try {
                    Thread.sleep(30);
                    if(name.equals("线程A")){
                        System.out.println(name+"卖出了"+(100-tickers+1)+"票,还有"+--tickers);
                    }
                    if(name.equals("线程B")){
                        System.out.println(name+"卖出了"+(100-tickers+1)+"票,还有"+--tickers);
                    }
                    if(name.equals("线程C")){
                        System.out.println(name+"卖出了"+(100-tickers+1)+"票,还有"+--tickers);
                    }
                    if(name.equals("线程D")){
                        System.out.println(name+"卖出了"+(100-tickers+1)+"票,还有"+--tickers);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
}
package com.模拟练习题五;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 2.给定一个list集合:{"张柏芝","刘德华","张亮","张靓颖","杨颖","黄晓明"}
     1.编写一个方法:将list集合中所有姓张的人员写入到D:\\a.txt中
     2.编写一个方法:将D:\\a.txt中所有姓张的人员信息读取出来并打印到控制台上
 * @author Administrator
 *
 */
public class Deme02 {
    public static void main(String[] args) throws IOException {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "张柏芝","刘德华","张亮","张靓颖","杨颖","黄晓明");
        writer(list);
        read(list);
    }

    private static void read(List<String> list) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        String line = br.readLine();
        System.out.println(line);
        br.close();
    }

    private static void writer(List<String> list) throws IOException {
        BufferedWriter bw  =  new BufferedWriter(new FileWriter("a.txt"));
        // TODO Auto-generated method stub
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).substring(0, 1).equals("张")){
                bw.write(list.get(i)+" ");
            }
        }
        bw.close();
    }
}
package com.模拟练习题六;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * 1.将用户在控制台上输出的5个数字按照大小顺序存入到D:\\xx.txt中,并读出显示在控制台上
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //固定数组大小
        int[] arr = new int[5];
        //键盘输入
        Scanner sc = new Scanner(System.in);
        //循环输入
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        
        //冒泡排序
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 0; j < arr.length-1-i; j++) {
                if(arr[j]>arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        
        //从缓冲区写入
        BufferedWriter bw = new BufferedWriter(new FileWriter("xx.txt"));
        for (int i : arr) {
            bw.write(i+" ");
        }
        bw.close();

    }
}
package com.模拟练习题六;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 2.现在有一个map集合如下:
      {1="张三丰",2="周芷若",3="汪峰",4="灭绝师太"}
      要求:
      1.将map集合中的所有信息显示到控制台上
      2.向该map集合中插入一个编码为5姓名为李晓红的信息
      3.移除该map中的编号为1的信息
      4.将map集合中编号为2的姓名信息修改为"周林"
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) {
        Map<Integer, String> map = new LinkedHashMap<>();
        map.put(1, "张三丰");
        map.put(2, "周芷若");
        map.put(3, "汪峰");
        map.put(4, "灭绝师太");
        System.out.println(map);
        
        map.put(5, "李小红");
        map.remove(1);
        map.put(2, "周林");
        System.out.println(map);
    }
}
package com.模拟练习题六;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

/**
 * 3.在ip为127.0.0.1的主机上有一个MySql的数据库,数据库名为db1.
  连接数据库的用户名和密码为root和123,该数据库中有一个表格为user,
  表中的数据如下:
              id     username     password
              1       abc          123
              2       def          456
              3       ghi          789
    请使用JDBC技术完成一个登录的案例(在控制台输入用户名和密码)登陆成功在控制台显示登录成功
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase", "root", "123456");
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = sc.nextLine();
        System.out.println("请输入密码:");
        String pass = sc.nextLine();
        String sql = "select * from user where username=? and password=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, name);
        pstmt.setString(2, pass);
        ResultSet rs = pstmt.executeQuery();
        if(rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("用户名密码错误");
        }
    }
}
package com.模拟练习题七;
/**
 * 2.有100份礼品,两人同时发送,当剩下的礼品小于10份的时候则不再送出,利用多线程模拟该过程并将线程的名称打印出来.
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) {
        pack p = new pack();
        new Thread(p,"线程A").start();
        new Thread(p,"线程B").start();
    }
}
class pack implements Runnable{
    static int number = 100;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            synchronized (this) {
                //小于0 聊天线程依次return
                if(number<=10){
                    return;
                }
                try {
                    //获取线程名字数
                    String name = Thread.currentThread().getName();
                    //判断是不是这个线程
                    if(name.equals("线程A")){
                        System.out.println(name+"发出了第"+(100-number+1)+"个,还有"+--number);
                    }
                    //睡眠30毫秒
                    Thread.sleep(30);
                    if(name.equals("线程B")){
                        System.out.println(name+"发出了第"+(100-number+1)+"个,还有"+--number);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package com.模拟练习题七;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 
 *3.取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,
 * 输出格式为:a(2)b(1)k(2)...
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //键盘接收有个字符串
        String str = sc.nextLine();
        //装换为字符数组
        char[] ch = str.toCharArray();
        //包含加1  不包含为1
        Map<Character, Integer> map = new HashMap<>();
        for (char c : ch) {
            map.put(c, !map.containsKey(c)? 1:map.get(c)+1);
        }
        //打印格式
        for(Character ch1 : map.keySet()){
            System.out.println(ch1+"("+map.get(ch1)+")");
        }
    }
}
package com.模拟练习题八;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 3.从键盘接受多个int型的整数,直到用户输入end结束
     要求:把所有的整数按倒序写到D:\\number.txt中
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws IOException {
        ArrayList<Integer> list = getScaaner();
        System.out.println(list);
        //冒泡排序
        for (int i = 0; i < list.size()-1; i++) {
            for (int j = 0; j < list.size()-1-i; j++) {
                int one = list.get(j);
                int two = list.get(j+1);
                if(one<two){
                    list.set(j, two);
                    list.set(j+1, one);
                }
            }
        }
        
        //遍历直接从缓冲区写入
        BufferedWriter bw = new BufferedWriter(new FileWriter("number.txt"));
        for (int i = 0; i < list.size(); i++) {
            bw.write(list.get(i)+" ");
        }
        bw.close();
    }

    private static ArrayList<Integer> getScaaner() {
        System.out.println("请输入整数");
        Scanner sc = new Scanner(System.in);
        //建一个集合用来接收键盘输入的字符串
        ArrayList<Integer> list = new ArrayList<>();
        //用正则判断输入的是否是整数+号表示多个的意思
        String regex = "[0-9]+";
        while(true){
            //如果输入的数是end就结束
            String num = sc.next();
            if((num).equals("end")){
                System.out.println("结束");
                return list;
            }else if(num.matches(regex)){
                list.add(Integer.parseInt(num));
            }else{
                System.out.println("输入的不是整数");
            }
        }
        /*System.out.println("请输入整数:");
        Scanner sc  = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();
        while(true){
            String num = sc.next();
            if(num.equals("end")){
                return list;
            }else{
                list.add(Integer.parseInt(num));
            }
        }*/
    }
}
package com.模拟练习题八;

import java.util.Scanner;

/*
 * 1.编写一个校验用户名的程序,检测键盘录入的用户名是否合法
     要求:用户名必须是6-10位之间的字母并且不能以数字开头
 */
public class Demo01 {
    public static void main(String[] args) {
        //键盘接收一条字符串
        String str = new Scanner(System.in).nextLine();
        //正则表达式   前面开头是a-zA-Z  ,{5,9}个
        String regex = "[a-zA-Z][a-zA-Z0-9]{5,9}";
        //判断是否符合正则表达式
        if(str.matches(regex)){
            System.out.println("输入的是正确的");
        }else{
            System.out.println("格式错误");
        }
        //第二种方法
        que(str);
    }

    private static void que(String str) {
        //字符串装换为字符数组
        char[] ch = str.toCharArray();
        //控制6-10个数
        if(ch.length>=6 && ch.length<=10){
            //判断是否是数字开头
            if(ch[0]>='0' && ch[0]<='9'){
                System.out.println("格式错误");
            }else{
                //从1元素开始   判断是否是符合0-9a-zA-Z
                for (int i = 1; i < ch.length; i++) {
                    if((ch[i]>='a' && ch[i]<='z') || (ch[i]>='A' && ch[i]<='Z') ||(ch[i]>='0' && ch[i]<='9')){
                    }else{
                        //发现不符合的直接return
                        System.out.println("格式错误");
                        return;
                    }
                }
                System.out.println("格式正确");
            }
        }
    }
}
package com.模拟练习题九;
/**
 * 1.将"goOd gooD stUdy dAy dAy up"每个单词的首字母转换成大写其余还是小写字母
 * (不许直接输出good good study day day up 要用代码实现)
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        String string = "goOd gooD stUdy dAy dAy up";
        //字符串转换为字符串数组
        String[] str = string.split(" +");
        //接收每一个字符数组中的元素  拼接
        String strend="";
        for (int i = 0; i < str.length; i++) {
            String end = str[i];
            //首字母大写  其他字母小写
            end = end.substring(0, 1).toUpperCase().concat(end.substring(1, end.length()).toLowerCase());
            strend+=end+" ";
        }
        System.out.println(strend);
    }
}
package com.模拟练习题九;
/**
 * 2.有100个限量版的水杯,但是只能通过实体店和官网才能进行购买,并且分别统计卖了多少。
 *   请用线程进行模拟并设置线程名称用来代表售出途径,再将信息打印出来。
    比如(实体店卖出第1个,总共剩余n个..)
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) {
        Shuibei s = new Shuibei();
        new Thread(s,"实体店").start();
        new Thread(s,"官网店").start();
    }
}
class Shuibei implements Runnable{
    //总量100
    static int number =100;
    //计数器
    int sums = 0;
    int sumg = 0;
    @Override
    public void run() {
        //无限循环
        while(true){
            //同步代码块
            synchronized (this) {
                if(number<0){
                    return;
                }
                try {
                    //睡眠30毫秒
                    Thread.sleep(30);
                    String name = Thread.currentThread().getName();
                    if(name.equals("实体店")){
                        sums++;
                        System.out.println(name+"卖出了第"+(100-number+1)+"还剩下"+--number);
                    }
                    if(name.equals("官网店")){
                        sumg++;
                        System.out.println(name+"卖出了第"+(100-number+1)+"还剩下"+--number);
                    }
                    
                    if(number==0){
                        System.out.println(sums);
                        System.out.println(sumg);
                        //number--一条线程进回来了,条件减一  不给第二条线程进来
                        number--;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package com.模拟练习题九;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 3.有一个Map集合里面存储的是学生的姓名和年龄,内容如下
 * {张三丰=21, 灭绝师太=38, 柳岩=28, 刘德华=40, 老鬼=36, 王二麻子=38}
    a.将里面的元素用两种遍历方式打印到控制台上
    b.将老鬼的年龄改成66
    c.将年龄大于24的学生姓名,存入到D:\\student.txt中
 * @author Administrator
 *
 */
public class Demo3 {
    public static void main(String[] args) throws IOException {
        Map<String, Integer> map = new HashMap<>();
        map.put("张三丰", 21);
        map.put("灭绝师太", 38);
        map.put("柳岩", 28);
        map.put("刘德华", 40);
        map.put("老鬼", 36);
        map.put("王二麻子", 38);
        System.out.println(map);
        
        map.put("老鬼", 66);
        BufferedWriter bw = new BufferedWriter(new FileWriter("student.txt"));
        for(String name : map.keySet()){
            if(map.get(name)>24){
                bw.write(name+" ");
            }
        }
        bw.close();
    }
}
package com.模拟练习题十;
/**
 * 1.有一个字符串"woaijavahajajavavahajavaaiwo"删除该字符串中所有的"java"并且统计删除了多少个“java”
 * @author Administrator
 */
public class Demo01 {
    public static void main(String[] args) {
        String strone = "woaijavahajajavavahajavaaiwo";
        String strjava = "java";
        int index = 0;
        int count=0;
        //记录第一次出现java的位置,直到没有结束循环
        while((index = strone.indexOf(strjava))!=-1){
            //把出现成java的字符串给去除掉
            strone = strone.substring(0,index).concat(strone.substring(index+strjava.length()));
            count++;
        }
        System.out.println(strone);
        System.out.println(count);
    }
}
package com.模拟练习题十;
/**
 * 2.有一辆班车除司机外只能承载80个人,假设前中后三个车门都能上车,如果坐满则不能再上车。
*         请用线程模拟上车过程并且在控制台打印出是从哪个车门上车以及剩下的座位数。比如:
*        (前门上车---还剩N个座...)
 */
public class Demo02 {
    public static void main(String[] args) {
        Bus b = new Bus();
        new Thread(b,"前门").start();
        new Thread(b,"中门").start();
        new Thread(b,"后门").start();
    }
}
class Bus implements Runnable{
    static int person=80;
    @Override
    public void run() {
        while(true){
            synchronized (this) {
                try {
                    if(person<=0){
                        return;
                    }
                    Thread.sleep(30);
                    String name = Thread.currentThread().getName();
                    if(name.equals("前门")){
                        System.out.println(name+"上了第"+(80-person+1)+"还有"+--person+"个座");
                    }
                    if(name.equals("中门")){
                        System.out.println(name+"上了第"+(80-person+1)+"还有"+--person+"个座");
                    }
                    if(name.equals("后门")){
                        System.out.println(name+"上了第"+(80-person+1)+"还有"+--person+"个座");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }    
}
package com.模拟练习题十一;

import java.util.Scanner;

/**
 * 1.输入一个字符串,分别统计出其中英文字母、空格、数字和其它字符的数量
 * 正则表达式
 * 英文  "[a-zA-Z]"
 * 空格 "\\s"
 * 数字 "[0-9]"
 */
public class Demo01 {
    public static void main(String[] args) {
        System.out.println("请输入字符串:");
        Scanner sc = new Scanner(System.in);
        String string = sc.nextLine();
        //转换为字符串
        char[] ch = string.toCharArray();
        String hanzi="[\u4e00-\u9fa5]";
        String shuzi = "[0-9]";
        String zifu = "[a-zA-Z]";
        String kongge = "\\s";
        //计数器
        int hanzi1= 0;
        int shuzi1 = 0;
        int zifu1 = 0;
        int kongge1 = 0;
        int qita=0;
        //遍历
        for (char c : ch) {
            if((c+"").matches(hanzi)){
                hanzi1++;
            }else if((c+"").matches(shuzi)){
                shuzi1++;
            }else if ((c+"").matches(zifu)){
                zifu1++;
            }else if((c+"").matches(kongge)){
                kongge1++;
            }else{
                qita++;
            }
        }
        System.out.println("数字:"+shuzi1+" 字母:"+zifu1+" 空格:"+kongge1+" 其他:"+qita+" 汉字:"+hanzi1);
    }
}
package com.模拟练习题十一;

import java.util.ArrayList;

/**
 * 2.定义一个实体类有姓名、学号、成绩(int类型)三个属性
    (1)在创建对象时给这些属性进行显示初始化
    (2)将学生的信息(姓名、学号、成绩)存入到适当的集合,并且根据学生成绩按照降序打印到控制台
    //遍历集合  拿出成绩  比较 >>冒泡排序
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) {
        Student stu  = new Student("张三",1,80);
        Student stu1  = new Student("李四",2,60);
        Student stu2  = new Student("王五",3,77);
        Student stu3  = new Student("赵六",4,90);
        ArrayList<Student> list = new ArrayList<>();
        list.add(stu);
        list.add(stu1);
        list.add(stu2);
        list.add(stu3);
        
        //冒泡排序
        for (int i = 0; i < list.size()-1; i++) {
            for (int j = 0; j < list.size()-1-i; j++) {
                //建立对象接收集合中的Student
                Student s = list.get(j);
                Student s1 = list.get(j+1);
                //比较成绩
                if(s.getScore()>s1.getScore()){
                    list.set(j, s1);
                    list.set(j+1, s);
                }
            }
        }
        for(Student st : list){
            System.out.println(st);
        }
    }
}
class Student{
    private String name;
    private int id;
    private int score;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public Student(String name, int id, int score) {
        super();
        this.name = name;
        this.id = id;
        this.score = score;
    }
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", id=" + id + ", score=" + score + "]";
    }
    
}
package com.模拟练习题十一;
/**
 * 3.同时开启两个线程,共同输出1-100之间的所有数字,并且将输出奇数的线程名称打印出来
 * if(i%2!=0){
 *         syso
 * }
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) {
        Qishu q = new Qishu();
        new Thread(q).start();
        new Thread(q).start();
    }
}
class Qishu implements Runnable{
    
    @Override
    public void run() {
        //1-100
        for (int i = 1; i < 100; i++) {
            synchronized (this) {    
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String name = Thread.currentThread().getName();
                //抢到执行的前程输出
                if(i%2!=0){
                    System.out.println(name+".."+i);
                }
            }
        }
        
    }
    
}
package com.模拟练习题十二;

import java.util.Scanner;

/**
 * 1.从控制台接受一串字符串(8分)
    (1)将该字符串转换成字符数组(2分)     toCharArray();
    (2)将该字符数组下标为偶数的字符打印倒控制台(3分)  if(i%2==0)
    (3)将该字符数组的第一个元素与最后一个元素互换(3分)   加一个交换的属性
 * @author Administrator
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        System.out.println("请输入一个字符串");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] ch = str.toCharArray();
        for (char c : ch) {
            System.out.print(c+" ");
        }
        System.out.println();
        for (int i = 0; i < ch.length; i++) {
            if(i%2==0){
                System.out.print(ch[i]+" ");
            }
        }
        System.out.println();
        char c = ch[0];
        ch[0] = ch[ch.length-1];
        ch[ch.length-1] = c;
        for (char c1 : ch) {
            System.out.print(c1+" ");
        }
    }
}
package com.模拟练习题十二;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2.按一下要求完成相应功能(12分) (不能用DBUtils等工具类)
    (1)设计一个工具类,定义一个方法名为getConnection的方法用来获取连接,相关的参数需要用形式参数的形式传入进去(4分)
    (2)有一个student如下
        id    name                age                    score
        1    zs                    18                     98
        2    ls                    24                     89
        3    wwk                    32                     100
        4    anni                25                     54
    将该表中每一条记录都封装成一个Student对象,(用a中的getConnection方法来获取连接
    其中数据库名称,用户名和密码可以自定义)不能直接给Student赋值(不如:Student = new Student("2s",18.98)),要获取数据库
    里面相应的内容,然后赋值给Student对象(4分)
    (3)将(2)中得到的Student对象存到list集合中并且用两种方式遍历出来(4分)
    (4)实现添加Student对象的方法
        public static int addStudent(Student student) {
            //要求传递一个Student对象,先判断该对象有没有,没有的话,添加,提示添加成功,有的话打印添加失败,并返回-1
        }
    (5)实现修改Student对象的方法
        public static int updateStudent(Student student) {
            //要求传递一个Student对象,先根据该对象id查询是否存在,有的话,进行修改操作,并提示修改成功,返回1,没有的话打印修改失败,并返回-1
        }
    (6)实现删除Student对象的方法
        public static int deleteStudentById(String id) {
            //根据id删除Student对象,删除成功返回1,删除失败返回-1
        }
    (7)实现获取所有Student对象的以下方法
        public static List<Student> getAllStudent1(){
        }
        public static List<Object[]> getAllStudent2(){
            //Object[]:中存储的是每个学生对象的信息,比如Object[] arr = {"zs",18,98}
        }
        public static List<Map<String,Object>> getAllStudent3(){
            //List<Map<String,Object>>:中存储的是Map集合,每个Map集合中存储的是该Student对象的属性值,其中key是String类型表示属性名称,
            //value为Object类型,代表该属性对应的值
        }
 * @author Administrator
 *
 */
public class Demo02 {
    static Connection con = JDBCUtils.getConnection();
    public static void main(String[] args) throws SQLException {
        List<Student> list = new ArrayList<>();
        add(con,list);
        Student stu = new Student("122",12,32);
//        System.out.println(addStudent(stu, list));
//        System.out.println(updateStudent(stu, con));
//         List<Object[]> list1 = getAllStudent2();
        List<Map<String,Object>> list1 = getAllStudent3();
        for (Map<String, Object> map : list1) {
            for(String key :map.keySet()){
                System.out.print(key+" = "+ map.get(key)+" ");
            }
            System.out.println();
        }
    }
    public static List<Map<String,Object>> getAllStudent3() throws SQLException{
        //List<Map<String,Object>>:中存储的是Map集合,每个Map集合中存储的是该Student对象的属性值,其中key是String类型表示属性名称,
        List<Map<String,Object>> list = new ArrayList<>();    
        //value为Object类型,代表该属性对应的值
        String sql = "select * from stu";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            Map<String,Object> map = new HashMap<>();
            map.put("name", rs.getString("name"));
            map.put("age", rs.getInt("age"));
            map.put("socre", rs.getInt("socre"));
            list.add(map);
        }
        return list;
    }
    
    public static List<Object[]> getAllStudent2() throws SQLException{
        //Object[]:中存储的是每个学生对象的信息,比如Object[] arr = {"zs",18,98}
         List<Object[]> list = new ArrayList<>();
            String sql = "select * from stu";
            PreparedStatement pstmt = con.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()){
                Object[] a = new Object[3];
                a[0] = rs.getString("name");
                a[1] = rs.getInt("age");
                a[2] = rs.getInt("socre");
                list.add(a);
            }
            return list;
    }
    
    public static List<Student> getAllStudent1(Connection con) throws SQLException{
        List<Student> list = new ArrayList<>();
        String sql = "select * from stu";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            Student s = new Student();
            s.setName(rs.getString("name"));
            s.setAge(rs.getInt("age"));
            s.setScore(rs.getInt("socre"));
            list.add(s);
        }
        return list;
        
    }
    /**
     * 数据库的修改
     * SQL语句的update 表名 set  列名=? where 类名=?
     * 遍历集合  将要添加的数据放在数据库中查找 没有就添加   有就返回-1
     * @param student
     * @param con
     * @return
     * @throws SQLException
     */
    public static int updateStudent(Student student,Connection con) throws SQLException {
        //要求传递一个Student对象,先根据该对象id查询是否存在,有的话,进行修改操作,并提示修改成功,返回1,没有的话打印修改失败,并返回-1
        String name = student.getName();
        int age = student.getAge();
        int score = student.getScore();        
        
        String sql ="select * from stu where name=?";
        PreparedStatement sptmt = con.prepareStatement(sql);
        sptmt.setString(1, name);
        ResultSet rs = sptmt.executeQuery();
        if(!rs.next()){
            System.out.println("没有的话打印修改失败");
            return -1;
        }else{
            String sql1 = "update stu set name=? where name= ?";
            PreparedStatement pstmt = con.prepareStatement(sql1);
            pstmt.setString(1, "撒即可");
            pstmt.setString(2, name);
            pstmt.executeUpdate();
            return 1;
        }
    }
    
    /**
     * 数据库的添加
     * SQL语句的insert into 表名 (列名,..) values (数据) 
     * 遍历集合  将要添加的数据放在数据库中查找 没有就添加   有就返回-1
     * @param student
     * @param list
     * @return
     * @throws SQLException
     */
    public static int addStudent(Student student,List<Student> list) throws SQLException{
        //要求传递一个Student对象,先判断该对象有没有,没有的话,添加,提示添加成功,有的话打印添加失败,并返回-1
        String name = student.getName();
        int age = student.getAge();
        int score = student.getScore();        
        
        for(Student stu : list){
            String sql = "select * from stu where name=? and age=? and socre=?";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setInt(2, age);
            pstmt.setInt(3, score);
            ResultSet rs = pstmt.executeQuery();
            //如果不存在  就添加
            if(!rs.next()) {
                String sql1 = "insert into stu (name ,age ,socre) values (?,?,?)";
                PreparedStatement pstmt1 = con.prepareStatement(sql1);
                pstmt1.setString(1, name);
                pstmt1.setInt(2, age);
                pstmt1.setInt(3, score);
                int two = pstmt1.executeUpdate();
                //判断是否添加成功  成功直接return   否则返回-1
                if (two != 0) {
                    System.out.println("添加成功");
                    return two;
                }
            }
        }
        System.out.println("添加失败");
        return -1;
    }
    /**
     * 将数据库中的数据添加到集合中  集合对象就是Student
     * @param con2
     * @param list
     * @throws SQLException
     */
    private static void add(Connection con2, List<Student> list) throws SQLException {
        //查询数据库
        String sql = "select * from stu";
        //发送SQL语句
        PreparedStatement pstmt = con.prepareStatement(sql);
        //解析SQL语句
        ResultSet rs = pstmt.executeQuery();
        //如果是符合条件   就添加
        while(rs.next()){
            Student s = new Student();
            s.setName(rs.getString("name"));
            s.setAge(rs.getInt("age"));
            s.setScore(rs.getInt("socre"));
            list.add(s);
        }
    
    }
}
class Student{
    private String name;
    private int age;
    private int score;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public Student(String name, int age, int score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
    }
    
}
package com.模拟练习题十三;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 1.设计一个interface MyUtil,该接口有两个抽象方法 
    创建一个类实现MyUtil接口并按以下要求实现两个抽象方法
    public abstract void sort(ArrayList<Integer> list);
    public abstract void filterChars(ArrayList<String> list);
    a.ArrayList集合排序方法:将传入的ArrayList集合元素进行进行排序(不能直接用Collections.sort()方法)
    //冒泡
    b.字符串过滤字母:将传入的ArrayList<String>集合中的每个元素中的字母过滤掉,比如(传入 hello123java,返回123)
    //字符串转数组       遍历条件符合[0-9]的添加
 * @author Administrator
 *
 */
public class Demo01 implements MyUtil{
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        Collections.addAll(list, 12,34,12,1,54,122);
        ArrayList<String> list2 = new ArrayList<>();
        Collections.addAll(list2, "123weq","hello123java");
        Demo01 d = new Demo01();
        d.sort(list);
        System.out.println();
        d.filterChars(list2);
    }

    @Override
    public void sort(ArrayList<Integer> list) {
        // TODO Auto-generated method stub
        for (int i = 0; i < list.size()-1; i++) {
            for (int j = 0; j < list.size()-1-i; j++) {
                int one = list.get(j);
                int two = list.get(j+1);
                if(one>two){
                    list.set(j, two);
                    list.set(j+1, one);
                }
            }
        }
        for (Integer integer : list) {
            System.out.print(integer+" ");
        }
    }

    @Override
    public void filterChars(ArrayList<String> list) {
        for (int i = 0; i < list.size(); i++) {
            char[] ch = list.get(i).toCharArray();
            String regex = "[0-9]";
            String str="";
            for (int j = 0; j < ch.length; j++) {
                if((ch[j]+"").matches(regex)){
                    str+=ch[j];
                }
            }
            list.set(i, str);
        }
        for (String string : list) {
            System.out.print(string+" ");
        }
    }
}
interface MyUtil{ 
    public abstract void sort(ArrayList<Integer> list);
    public abstract void filterChars(ArrayList<String> list);
}
package com.模拟练习题十三;

import java.util.ArrayList;

/**
 * 2.某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,假设公司有100个员工,
 * 利用多线程模拟年会入场过程,
    并分别统计每个入口入场的人数,以及每个员工拿到的彩票的号码。线程运行后打印格式如下:
    编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
    编号为: 1 的员工 从后门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
    //.....
    从后门入场的员工总共: 13 位员工
    从前门入场的员工总共: 87 位员工
 * @author Administrator
 * 双色就的号码不重复    建立一个产生7位不重复整数的方法  hashset不重复   list接收
 * 集合长度为条件    往集合中添加  如果集合已经包含就不添加
 */
public class Demo02 {
    public static void main(String[] args) {
        Number num = new Number();
        new Thread(num,"前门").start();
        new Thread(num,"后门").start();
    }
}
class Number implements Runnable{
    static int person=100;
    int sumq=0;
    int sumh = 0;
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            synchronized (this) {
                try {
                    if(person<0){
                        return;
                    }
                    Thread.sleep(30);
                    String name = Thread.currentThread().getName();
                    if(name.equals("前门")){
                        sumq++;
                        System.out.print("编号为:"+(100-person+1)+"  的员工 从"+ name + "入场! 拿到的双色球彩票号码是:");
                        --person;
                        arr();
                    }
                    if(name.equals("后门")){
                        sumh++;
                        System.out.print("编号为:"+(100-person+1)+"  的员工 从"+ name + "入场! 拿到的双色球彩票号码是:");
                        --person;
                        arr();
                    }
                    if(person==0){
                        System.out.println("从后门入场的员工总共:"+sumh+"位员工");
                        System.out.println("从后门入场的员工总共:"+sumq+"位员工");
                        person--;
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public static void arr(){
        ArrayList<Integer> list = new ArrayList<>();
        while(list.size()<7){
            int num  = (int) (Math.random()*30);
            if(!list.contains(num)){
                list.add(num);
            }
        }
        System.out.println(list);
    }
}
package com.模拟练习题十三;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 3.    有一个数组 String arr[]={"abc","bad","abc","aab","bad","cef","jhi"};
    a.    创建一个ArrayList,将数组里面的元素添加进去,但元素不能重复 (该数组不变)
        //判断是否包含
    b.    创建一个 TreeSet,将数组里面的元素按升序序存入该集合里,并且不能去重
    c.  将数组里面的所有元素存入到项目根目录下的String.txt文件中
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws IOException {
        String arr[]={"abc","bad","abc","aab","bad","cef","jhi"};
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if(!list.contains(arr[i])){
                list.add(arr[i]);
            }
        }
        System.out.println(list);
        ArrayList<String> list1 = new ArrayList<>();
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 0; j < arr.length-1-i; j++) {
                if(arr[j].compareTo(arr[j+1])<0){
                    String str = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = str;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            list1.add(arr[i]);
        }
        
        BufferedWriter bw  = new BufferedWriter(new FileWriter("String.txt"));
        for (String string : list1) {
            bw.write(string+" ");
        }
        bw.close();
    }
}
package com.模拟练习题十四;

import java.util.ArrayList;

/**
 * 3.有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300}; 
    创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”,随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
    
    抽奖箱1 又产生了一个 10 元大奖
    抽奖箱2 又产生了一个 100 元大奖    
    //.....
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) {
        Money m = new Money();
        new Thread(m,"抽奖箱1").start();
        new Thread(m,"抽奖箱2").start();
    }
}
class Money implements Runnable{
    int[] arr = {10,5,20,50,100,200,500,800,2,80,300}; 
    ArrayList<Integer> list = new ArrayList<>();
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            synchronized (this) {
                int num = (int) (Math.random()*arr.length);
                if(list.size()==arr.length){
                    return;
                }
                //如果集合中不包含这个元素   就可以打印
                if(!list.contains(num)){
                    list.add(num);
                    
                    try {
                        Thread.sleep(30);
                        String name = Thread.currentThread().getName();
                        if(name.equals("抽奖箱1")){
                            System.out.println(name +"又产生了一个 "+arr[num]+" 元大奖");
                        }
                        if(name.equals("抽奖箱2")){
                            System.out.println(name +"又产生了一个 "+arr[num]+" 元大奖");
                        }
                        
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
            }
        }
    }
    
}
package com.模拟练习题十五;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * //思考题:第一个String代表的是学科名称比如"java学科",第二个String代表:开班的班级名称"JavaEE0320" ,ArrayList代表该班级里的学生
        HashMap<String,ArrayList<HashMap<String,ArrayList<Student>>>> hs =
                    new HashMap<String,ArrayList<HashMap<String,ArrayList<Student>>>>();
 * //思考题:ArrayList<Integer> list 里面存放的是学生成绩{80,90,100,60,50,30,55,98,36},对ArrayList集合中的成绩进行统计,将统计后的结果放入
    map中,"及格的学员数量" = 5   "不及格的学员数量"=4
   //思考题:使用LinkedList完成数组去重?
 * @author JX
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        HashMap<String,ArrayList<HashMap<String,ArrayList<Student>>>> hs =
                new HashMap<String,ArrayList<HashMap<String,ArrayList<Student>>>>();
        
        ArrayList<Student> stu = new ArrayList<>();
        stu.add(new Student("张三",30));
        stu.add(new Student("张三2",29));
        stu.add(new Student("张三3",33));
        ArrayList<Student> stu1 = new ArrayList<>();
        stu1.add(new Student("张四",31));
        stu1.add(new Student("张四2",22));
        stu1.add(new Student("张四3",35));
        ArrayList<Student> stu2= new ArrayList<>();
        stu2.add(new Student("张五",40));
        stu2.add(new Student("张五2",49));
        stu2.add(new Student("张五3",43));
        
        HashMap<String,ArrayList<Student>> hashmap = new HashMap<>();
        hashmap.put("JavaEE0320", stu);
        HashMap<String,ArrayList<Student>> hashmap1 = new HashMap<>();
        hashmap.put("JavaEE0420", stu1);
        HashMap<String,ArrayList<Student>> hashmap2 = new HashMap<>();
        hashmap.put("JavaEE0520", stu2);
        
        ArrayList<HashMap<String,ArrayList<Student>>> list = new ArrayList<>();
        list.add(hashmap);
        list.add(hashmap1);
        list.add(hashmap2);
        
        hs.put("java学科", list);
        
        for(String key : hs.keySet()){
            System.out.print(key+" ");
            for(HashMap<String,ArrayList<Student>> hashmapp : hs.get(key) ){
                for(String key1 : hashmapp.keySet()){
                    System.out.println(key1+" ");
                    for(Student st : hashmapp.get(key1)){
                        System.out.println(st);
                    }
                }
            }
        }
    }
}
class Student{
    private String name;
    private int age;
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Student(String name) {
        super();
        this.name = name;
    }

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }


}
package com.第九轮;

import java.util.ArrayList;
import java.util.List;

//第一部分是固定的字符串bjhmsy53,第二部分_001一直到_100,比如:bjhmsy53_001,bjhmsy53_002....,bjhmsy_100),
public class Demo01 {
    public static void main(String[] args) {
        Number nun = new Number();
        new Thread(nun,"线程A").start();
        new Thread(nun,"线程B").start();
    }
}
class Number implements Runnable{
    String strone = "bjhmsy53";
    int num =100;
    ArrayList<Integer> list  = new ArrayList<>();
    ArrayList<String> listA  = new ArrayList<>();
    ArrayList<String> listB  = new ArrayList<>();
    @Override
    public void run() {
        while(true){
            synchronized (this) {
                if(list.size()>=10){
                    return;
                }
                int number = (int) (Math.random()*100+1);
                try {
                    if(!list.contains(number)){
                        list.add(number);
                        String name = Thread.currentThread().getName();
                        String numberstr = "";
                        if(number<10){
                            numberstr="_00"+number;
                        }else if(number<100){
                            numberstr="_0"+number;
                        }else if(number==100){
                            numberstr="_"+number;
                        }
                        if(name.equals("线程A")){
                            listA.add(numberstr);        
                        }
                        Thread.sleep(30);
                        if(name.equals("线程B")){
                            listB.add(numberstr);        
                        }
                        
                        if(list.size()==10){
                            System.out.print("线程A: ");
                            for(String str : listA){
                                System.out.print(strone+str+" ");
                            }
                            System.out.println("共"+listA.size());
                            
                            System.out.print("线程B: ");
                            for(String str : listB){
                                System.out.print(strone+str+" ");
                            }
                            System.out.println("共"+listB.size());
                            list.add(11);
                        }
                    }
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }        
    }    
}
package com.第九轮;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 1.统计各个文件的个数
 * 2.将1中录入的文件夹包含子文件夹的所有java文件拷贝到E:\\java\\文件夹中
    分别利用字节流,字符流,缓冲流完成
 * @author Administrator
 *
 */
public class Demo04 {
    public static void main(String[] args) throws IOException {
        Map<String, Integer> map = new HashMap<>();
        File file = getFile();
        ArrayList<File> list = new ArrayList<>();
        add(map,file,list);
        for(String key : map.keySet()){
            System.out.println(key+" = "+map.get(key));
        } 
        System.out.println();
        System.out.println(list);
        
        File dest = new File("E:\\java");
        if(!dest.exists()){
            dest.mkdirs();
        }
        copy(list,dest);
    }

    private static void copy(ArrayList<File> list, File dest) throws IOException {
        for(File file : list){
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(dest,file.getName())));
            byte[] by = new byte[1024*8];
            int len = 0;
            while((bis.read(by))!=-1){
                bos.write(by, 0, len);
            }
        }
        
    }

    private static void add(Map<String, Integer> map, File file, ArrayList<File> list) {
        File[] files=  file.listFiles();
        if(files!=null){
            for (File file2 : files) {
                if(file2.isFile()){
                    String name = file2.getName().toLowerCase().substring(file2.getName().indexOf("."));
                    map.put(name, !map.containsKey(name)? 1: map.get(name)+1);
                    if(file2.getName().endsWith(".java")){
                        list.add(file2);
                    }
                }else if(file2.isDirectory()){
                    add(map, file2,list);
                }
            }
        }
        
    }

    private static File getFile() {
        System.out.println("请输入一个文件夹的路径:");
        Scanner sc = new Scanner(System.in);
        while(true){
            String str = sc.nextLine();
            File file = new File(str);
            if(!file.exists()){
                System.out.println("输入的文件夹路径不存在,请重新输入!");
            }else if(file.isFile()){
                System.out.println("输入的是文件的路径,请重新输入!");
            }else
                return file;
        }
    }
}
package com.第七轮;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 递归获取所有的MP3的名字 和路径map(名字,路径)
 * 用户输入编号  map(编号,名字)
 * @author Administrator
 *
 */
public class Demo05 {
    public static void main(String[] args) throws Exception {
        //先获取map(编号,名字)
        Map<String, String> mapsong = new HashMap<>();
        addmapsong(mapsong);
        System.out.println(mapsong);
        
        Map<String, File> mapfile = new HashMap<>();
        File file = new File("E:\\IOO");
        addmapfile(mapfile, file);
        System.out.println(mapfile);
        
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("1:根据编号下载   2:下载以上所有歌曲  3:退出");
            int num = sc.nextInt();
            switch (num) {
            case 1:
                System.out.println("请输入您要下载的歌曲编号");
                String number = sc.next();
                copy(number,mapsong,mapfile);
                break;
            case 2:
                copyall(mapfile);
                break;
            case 3:
                System.out.println("再见");
                return;
            default:
                System.out.println("不存在此编号");
                break;
            }
        }
    }

    private static void copyall( Map<String, File> mapfile) throws IOException {
        File newfile = new File("E:\\songs");
        if(!newfile.exists()){
            newfile.mkdirs();
        }
        for(String name : mapfile.keySet()){
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(mapfile.get(name)));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(newfile,mapfile.get(name).getName())));
            byte[] by = new  byte[1024*8];
            int len = 0;
            while((len=bis.read(by))!=-1){
                bos.write(by, 0, len);
            }
            bis.close();
            bos.close();
        }
        
    }

    private static void copy(String number, Map<String, String> mapsong, Map<String, File> mapfile) throws IOException {
        String name = mapsong.get(number);        
        File file = mapfile.get(name+".mp3");
        
        File newfile = new File("E:\\songs");
        if(!newfile.exists()){
            newfile.mkdirs();
        }
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(newfile,file.getName())));
        byte[] by = new  byte[1024*8];
        int len = 0;
        while((len=bis.read(by))!=-1){
            bos.write(by, 0, len);
        }
        bis.close();
        bos.close();
    }

    private static void addmapfile(Map<String, File> mapfile, File file) {
        File[] files = file.listFiles();
        if(files!=null){
            for (File file2 : files) {
                if(file2.isFile() && file2.getName().toLowerCase().endsWith(".mp3")){
                    mapfile.put(file2.getName(), file2);
                }else if(file2.isDirectory()){
                    addmapfile(mapfile, file2);
                }
            }
        }
    }

    private static void addmapsong(Map<String, String> mapsong) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("songs.txt"));
        String line = null;
        while((line = br.readLine())!=null){
            String[] string = line.split("=");
            mapsong.put(string[0], string[1]);
        }
        br.close();
    }
}
package com.fdb06;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 在当前项目下有一个student.txt  文件里的数据如下:
    张三丰=21
    灭绝师太=38
    柳岩=28
    刘德华=40
    老鬼=36
    皱市明=21
说明:(张三丰=21 其中 张三丰:姓名,21:年龄)
    a.将文件里的数据读取出来,打印到控制台上 (为了方便操作可以定义Student类,属性name、)
    b.循环显示菜单“请选择您要进行的操作:1.根据姓名查询年龄 2.根据年龄查询姓名 3.退出”
        举例:
        用户输入1
            控制台打印:请输入姓名
            用户输入:张三丰
            控制台打印:张三丰年龄为21岁
            如果输入的姓名不存在,则循环输入,直到存在为止
        用户输入2
            控制台打印:请输入年龄
            用户输入:21
            查询结果:年龄为21岁的人员信息如下:
            张三丰(注意:年龄为21岁的可能不止一个)
            如果输入的年龄不存在,则继续输入,直到存在为止
        用户输入3
            退出系统打印:欢迎下次再来,拜拜
    
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        BufferedReader br = new BufferedReader(new FileReader("student.txt"));
        String line = null;
        while((line = br.readLine())!=null){
            String[] str = line.split("=");
            map.put(str[0], Integer.parseInt(str[1]));
            System.out.println(line);
        }
        br.close();
        
        while(true){
            System.out.println("请选择您要进行的操作:1.根据姓名查询年龄 2.根据年龄查询姓名 3.退出");
            int num = sc.nextInt();
            switch (num) {
            case 1:
                while(true){            
                    System.out.println("亲输入姓名");
                    String name = sc.next();
                    if(cun(name,map)){
                        break;
                    }
                }
                break;
            case 2:
                while(true){
                    System.out.println("请输入年龄");
                    int age = sc.nextInt();
                    if(qyery(age,map)){                        
                        break;
                    }
                }
                break;
            case 3:
                System.out.println("欢迎下次再来,拜拜");
                return;

            default:
                System.out.println("没有此编号");
                break;
            }
        }
    }

    private static boolean qyery(int age, Map<String, Integer> map) {
        ArrayList<String> list = new ArrayList<>();
        for(String key : map.keySet()){
            if(age==map.get(key)){
                list.add(key);
            }
        }
        if (list.size() != 0) {
            System.out.print(age + "有:");
            for (String name : list) {
                System.out.print(name);
            }
            return true;
        }

        System.out.println("没有这个岁数");
        return false;
    }

    private static boolean cun(String name, Map<String, Integer> map) {
        for(String key : map.keySet()){
            if(name.equals(key)){
                System.out.println(name+"岁数为"+map.get(key));
                return true;
            }
        }
        System.out.println("不存在,请重新输入");
        return false;
    }
}
package com.fdb05;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;

/**
 * 项目根路径下有个questions.txt文件内容如下:
        5+5
        150-25
        155*155
        2555/5
    要求:读取内容计算出结果,将结果写入到results.txt文件中
        5+5=10
        //....
 * @author Administrator
 *
 */
public class Demo02 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("questions.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("results.txt"));
        String line = null;
        while((line=br.readLine())!=null){
            
            char[] ch = line.toCharArray();
            
            String fuhao ="";
            for (int i = 0; i < ch.length; i++) {
                if(ch[i]>'9' || ch[i]<'0'){
                    fuhao=ch[i]+"";
                    System.out.println(fuhao);
                }
            }
            if(fuhao.equals("+")){
                String[] str=line.split("[+]");
                int sum = Integer.parseInt(str[0])+Integer.parseInt(str[1]);
                bw.write(str[0]+"+"+str[1]+"="+sum);
                bw.newLine();
            }
            if(fuhao.equals("*")){
                String[] str=line.split("[*]");
                int sum = Integer.parseInt(str[0])*Integer.parseInt(str[1]);
                bw.write(str[0]+"*"+str[1]+"="+sum);
                bw.newLine();
            }
            if(fuhao.equals("-")){
                String[] str=line.split("[-]");
                int sum = Integer.parseInt(str[0])-Integer.parseInt(str[1]);
                bw.write(str[0]+"-"+str[1]+"="+sum);
                bw.newLine();
            }
            if(fuhao.equals("/")){
                String[] str=line.split("[/]");
                int sum = Integer.parseInt(str[0])/Integer.parseInt(str[1]);
                bw.write(str[0]+"/"+str[1]+"="+sum);
                bw.newLine();
            }
            bw.flush();
        }
    }
}

这差不多就是javaee基础阶段的题目了,我一个星期写了1.2W行代码,基本巩固了,如果有兴趣的朋友,可以只复制题目,不用看我的代码,这样一边下来,基础阶段的编码基本不成问题了.

 

补充几个反射的题目

package com.demo03;

import java.lang.reflect.Method;

/**
 *编写一个类,怎加一个实例的方法用于打印一条字符串
 *并使用反射的手段创建该类的对象,并调用该类的方法
 * @author Administrator
 */
public class Demo01 {
    public static void main(String[] args) throws Exception {
        //获取字节码对象
        Class clazz = Class.forName("com.demo03.Test1");
        //创建对象
        Test1 t = (Test1)clazz.newInstance();
        //获取方法
        Method method = clazz.getMethod("print", String.class);
        //调用方法
        method.invoke(t, "dads");
    }
}
class Test1{
    public void print(String str){
        System.out.println(str);
    }
}
package com.demo03;

import java.lang.reflect.Method;
import java.util.Scanner;

/*4.编写一个类A,增加一个实例方法showString,用于打印一条字符串,
在编写一个类TestA ,作为客户端,用键盘输入一个字符串,该字符串就是类A的全名,使用反射机制创建该类的对象,
并调用该对象中的方法showString*/
public class Demo02 {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        String namecalss = sc.nextLine();
        Class clazz = Class.forName(namecalss);
        Test2 t = (Test2)clazz.newInstance();
        Method method = clazz.getMethod("showString");        
        method.invoke(t);
    }
}
class Test2{
    public void showString(){
        System.out.println("showString");
    }
}
package com.demo03;

import java.lang.reflect.Field;

/**
 * 5. 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.   
    public void setProperty(Object obj, String propertyName, Object value){   
    }
 * @author Administrator
 *
 */
public class Demo03 {
    public static void main(String[] args) throws Exception {
        Demo03 d = new Demo03();
        /*Test3 t = new Test3();
        d.setProperty(t, "name", "张三");*/
        Test3 t = new Test3("李四");
        d.getProperty(t, "name");
        
    }
    public void setProperty(Object obj, String propertyName, Object value) throws Exception{   
        Class clazz  = Class.forName("com.demo03.Test3");
        Field declaredField = clazz.getDeclaredField(propertyName);
        declaredField.setAccessible(true);
        declaredField.set(obj, value);
        System.out.println(declaredField.get(obj));
    }
    
    public void getProperty(Object obj, String propertyName) throws Exception{
        Class clazz  = Class.forName("com.demo03.Test3");
        Field declaredField = clazz.getDeclaredField(propertyName);
        declaredField.setAccessible(true);    
        System.out.println(declaredField.get(obj));
    }
}
class Test3{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Test3(String name) {
        super();
        this.name = name;
    }

    public Test3() {
        super();
        // TODO Auto-generated constructor stub
    }
    
}
package com.demo03;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 *6.定义一个标准的JavaBean,名叫Person,包含属性name、age。
    使用反射的方式创建一个实例、调用构造函数初始化name、age,使用反射方式调用setName方法对名称进行设置,
    不使用setAge方法直接使用反射方式对age赋值。
 * @author Administrator
 *
 */
public class Demo04 {
    public static void main(String[] args) throws Exception {
        Class clazz  = Class.forName("com.demo03.Test4");
        Constructor constructor = clazz.getConstructor(String.class,int.class);
        Test4 t = (Test4)constructor.newInstance("李四",24);
        Method method = clazz.getMethod("setName", String.class);
        method.invoke(t, "lisi");
        Field declaredField = clazz.getDeclaredField("age");
        declaredField.setAccessible(true);
        declaredField.set(t, 23);
        System.out.println(t);
    }
}
class Test4{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Test4(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Test4() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Test4 [name=" + name + ", age=" + age + "]";
    }
    
}

有什么问题,我们共同研究,接下来,我将进入javaEE阶段.

posted on 2017-02-10 18:07  白杨无忧  阅读(8288)  评论(3编辑  收藏  举报