入学测试

package com.itheima;
public class Test1 {
    /**
     1、 写一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间。
     *
     * @param args
     *
     */
    public static void main(String[] args) {
        @SuppressWarnings("unchecked")
        List<String> arrayListProxy = (List<String>) Proxy.newProxyInstance(
        /* 定义代理类的加载器,用于创建类的对象 */
        ArrayList.class.getClassLoader(),
        /* 代理类要实现的接口列表 */
        ArrayList.class.getInterfaces(),
        /* 指派方法调用的处理程序,匿名内部类 */
        new InvocationHandler() {
            // 目标对象
            private ArrayList<String> taret = new ArrayList<String>();

            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                // 开始时间
                long startTime = System.currentTimeMillis();
                TimeUnit.MICROSECONDS.sleep(1);
                // 实际调用的方法,并接受方法的返回值
                Object obj = method.invoke(taret, args);
                // 结束时间
                long endTime = System.currentTimeMillis();
                System.out.println("[" + method.getName()+ "]需要的时间"
                        + (endTime — startTime) + "毫秒");
                // 返回实际调用的方法的返回值
                return obj;
            }
        });
        arrayListProxy.add("abc");
        arrayListProxy.add("abcdf");
        arrayListProxy.add("abcdefg");
        System.out.println("..........................");
        for (String i : arrayListProxy) {
            System.out.println("i=" + i);
        }      
    }
}

 

package com.itheima;
public class Test2 {
    /**
     2、 编写一个类,在main方法中定义一个Map对象(采用泛型),加入若干个对象, 然后遍历并打印出各元素的key和value。
     *
     * @param args
     */
    public static void main(String[] args) {
        
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("小赵", 12);
        map.put("小钱", 21);
        map.put("小孙", 25);
        map.put("小李", 9);
        //先获取map集合的所有键的Set集合,keyset();
        Set<String> set = map.keySet();
        //迭代
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String key = it.next();
            //有了键通过map集合的get方法获取其对应的值
            Integer value = map.get(key);
            System.out.println("key="+key+"   "+"value="+value);
        }
    }
}

package com.itheima;

public class Test3 {
    /**
      3、 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩),然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
    
     * @param args
     */
    public static void main(String[] args)throws IOException{
        // 自定义强制反转的比较器
        Comparator<Student> cmp = Collections.reverseOrder();
        // 以下把比较器作为参数传递
        Set<Student> stus = StudentInfoTool.getStudents(cmp);
            StudentInfoTool.writeToFile(stus);
    }
}
//定义学生类
class Student implements Comparable<Student> {
    private String name;
    private int chinese,english,maths;
    private int sum;

    Student(String name, int chinese, int english, int maths) {
        this.name = name;
        this.chinese = chinese;
        this.english = english;
        this.maths = maths;
        sum = chinese + english + maths;
    }

    public String getName() {
        return name;
    }

    public int getSum() {
        return sum;
    }
    //覆盖hashCode方法
    public int hashCode() {
        return name.hashCode()+sum * 78;
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof Student))
            throw new ClassCastException("类型不匹配");
        Student s = (Student) obj;
        return this.name.equals(s.name) && this.sum == s.sum;
    }
    // 实现接口中的方法,分数相同再比较姓名。如果总分和姓名都相同,就是同一个人。
    public int compareTo(Student s) {
        int num = new Integer(this.sum).compareTo(new Integer(s.sum));
        if (num == 0)
            return this.name.compareTo(s.name);
        return num;
    }

    public String toString() {
        return "student["+"姓名:"+name+",     "+"语文:"+chinese+",     "+"英语:"+english +",     "+"数学:"+maths+"]";
    }
}
//定义学生工具类
class StudentInfoTool {
    // 不带比较器的比较
    public static Set<Student> getStudents() {
        return getStudents(null);
    }
    // 带自定义比较器的比较
    public static Set<Student> getStudents(Comparator<Student> cmp){
        //读取键盘
        BufferedReader bufr = new BufferedReader(new InputStreamReader(
                System.in));
        String line = null;
        Set<Student> stus = null;
        if(cmp==null)
            stus=new TreeSet<Student>();
        else
            stus = new TreeSet<Student>(cmp);
            try {
                while ((line = bufr.readLine()) != null) {
                    // 输入over就结束
                    if ("over".equals(line))
                        break;
                    // 以逗号分隔输入的信息
                    String[] info = line.split(",");
                    // 字符串要转换为整形
                    Student stu = new Student(info[0], Integer.parseInt(info[1]),
                            Integer.parseInt(info[2]), Integer.parseInt(info[3]));
                    stus.add(stu);
                }
            } catch (NumberFormatException e1) {
                System.out.println("输入格式错误,输入格式为:name,30,30,30");
            } catch (IOException e1) {
                System.out.println("读取数据失败");
            }
        try {
            bufr.close();
        } catch (IOException e) {
            System.out.println("关闭失败");
        }
        return stus;
    }

    public static void writeToFile(Set<Student> stus) throws IOException{
        BufferedWriter bufw = null;
            bufw = new BufferedWriter(new FileWriter("E:\\stuinfo.txt"));
        for (Student stu : stus) {        
            bufw.write(stu.toString() + "\t");
            bufw.write(stu.getSum() + "");    
            bufw.newLine();    
            bufw.flush();        
        }    
            bufw.close();
        
    }
}

 

package com.itheima;
public class Test4 {
    /**
     4、 取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" , 输出格式为:a(2)b(1)k(2)...
     *
     * @param args
     */
    public static void main(String[] args) {
        String str = "abcdekka27qoq";
        System.out.println(charCount(str));
        
    }
    public static String charCount(String str){
        //将字符串转成字符数组
        char[] chs = str.toCharArray();
        //定义集合(打印有顺序使用TreeMap集合)
        TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
        int count =0;
        //遍历字符数组
        for(int x=0;x<chs.length;x++){
            //判断是不是字母
            if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
                continue;
            //chs[x]作为键找集合
            Integer value = tm.get(chs[x]);
            
            if(value!=null)
                count=value;
            count++;
            tm.put(chs[x], count);
            count=0;

        }
        //定义缓冲区
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
        //迭代
        Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
        while(it.hasNext()){
            Map.Entry<Character,Integer> me = it.next();
            Character ch = me.getKey();
            Integer value = me.getValue();
            sb.append(ch+"("+value+")");
        }
        return sb.toString();
    }
}

package com.itheima;
public class Test5 {
    /**
     5、 将字符串中进行反转。abcde ——> edcba
     * @param args
     */
    public static void main(String[] args) {
        String str = "abcde";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str){
        //将字符串转成字符数组
        char[] chs = str.toCharArray();
        reverse(chs);
        //将字符数组转成字符串
        return new String(chs);
    }
    //反转数组
    private static void reverse(char[] chs) {
        for(int start=0,end=chs.length—1;start<end;start++,end——){
            swap(chs,start,end);
        }
    }
    //换位置
    private static void swap(char[] chs, int start, int end) {
        char temp = chs[start];
        chs[start] = chs[end];
        chs[end] = temp;
    }
}

package com.itheima;
public class Test6 {
    /**
     6、 已知一个类,定义如下:
        package cn.itcast.heima;
        public class DemoClass {
           publicvoid run() {
          System.out.println("welcome to heima!"); } }
        (1)写一个Properties格式的配置文件,配置类的完整名称。
        (2)写一个程序,读取这个Properties配置文件,获得类的完整名称并加载这个类,用反射 的方式运行run方法。
     *
     * @param args
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) throws Exception {
        // 用Properties类加载配置文件
        Properties props = new Properties();
        InputStream fis = Test6.class.getClassLoader().getResourceAsStream(
                "com/itheima/Test6.Properties");
        props.load(fis);
        fis.close();
        // 取出类的完整名称
        String className = props.getProperty("className");
        System.out.println(className);
        DemoClass dc = new DemoClass();
        //加载类
        Class clazz = Class.forName(className);
        Method method = clazz.getMethod("run");
        method.invoke(dc);
    }
}

当前目录建一个Test6.Properties 内存入:className=cn.itcast.heima.DemoClass

package cn.itcast.heima;
public class DemoClass {
    public void run() {
        System.out.println("welcome to heima!");
    }
}

package com.itheima;
public class Test7 {
    /**
     7、 有一个类为ClassA,有一个类为ClassB,在ClassB中有一个方法b,此方法抛出异常,在ClassA类中有一个方法a,请在这个方法中调用b,然后抛出异常。 在客户端有一个类为TestC,有一个方法为c,请在这个方法中捕捉异常的信息。 完成这个例子,请说出java中针对异常的处理机制。
     *
     * @param args
     */
    /*
    1,处理方式有两种:try 或者 throws。
            try { 需要被检测的代码;}
            catch ( 异常类 变量 ) { 处理异常的代码;(处理方式) }
            finally { 一定会执行的语句; }
    2,调用到抛出异常的功能时,抛出几个,就处理几个。一个try对应多个catch。
    3,多个catch,父类的catch放到最下面。
    4,catch内,需要定义针对性的处理方式。不要简单的定义printStackTrace,输出语句。也不要不写。
当捕获到的异常,本功能处理不了时,可以继续在catch中抛出。
    */
    public static void main(String[] args) {
        TestC.c();
    }
}

class ClassA {
    public static void a() throws Exception {
        ClassB.b();
    }
}

class ClassB {
    public static void b() throws Exception {
        throw new Exception("方法b异常");
    }
}

class TestC {
    public static void c() {
        try {
            ClassA.a();
        } catch (Exception e) {
            System.out.println(e.getMessage()+"..."+e.toString());
        }
    }

package com.itheima;
public class Test8 {
    /**
     8、 存在一个JavaBean,它包含以下几种可能的属性:
         1:boolean/Boolean
         2:int/Integer
         3:String
         4:double/Double
     属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
         String类型的默认值为字符串"itheima.com"
         int/Integer类型的默认值为100
         boolean/Boolean类型的默认值为true
         double/Double的默认值为0.01D.
     只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
     *
     * @param args
     */
    public static void main(String[] args) {
        JavaBean jb = new JavaBean();
        jb.setString("itheima.com");
        jb.setInteger(100);
        jb.setBooleam(true);
        jb.setDoublo(0.01D);
        System.out.println("String类型的值="+jb.getString()+"\t\n"
                            +"int/Integer类型的值="+jb.getInteger()+"\t\n"
                            +"boolean/Boolean类型的值="+jb.isBooleam()+"\t\n"
                            +"double/Double的值="+jb.getDoublo());
    }
}


package com.itheima;
public class JavaBean {
    private String string ;
    private Integer integer;
    private Boolean booleam ;
    private Double doublo ;

    public String getString() {
        return string;
    }
    public void setString(String string) {
        this.string = string;
    }
    public Integer getInteger() {
        return integer;
    }
    public void setInteger(Integer integer) {
        this.integer = integer;
    }
    public Boolean isBooleam() {
        return booleam;
    }
    public void setBooleam(Boolean booleam) {
        this.booleam = booleam;
    }
    public Double getDoublo() {
        return doublo;
    }
    public void setDoublo(Double doublo) {
        this.doublo = doublo;
    }
}

 

package com.itheima;
public class Test9 {
    /**
     9、 使用TCP协议写一个可以上传文件的服务器和客户端。
     *
     * @param args
     */
    public static void main(String[] args) {    
    }
}
class  Client{
    public static void main(String[] args) throws Exception{
        Socket s = new Socket("192.168.1.102",10001);
        BufferedReader bufr =
            new BufferedReader(new FileReader("F:\\1.mp3"));

        //定义目的,将数据写入到socket输出流。发给服务端。
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        String line = null;
        while((line=bufr.readLine())!=null){
            out.println(line);
        }
        s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记—1.  

        //定义一个socket读取流,读取服务端返回的信息。      
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str = bufIn.readLine();
        System.out.println(str);
        bufr.close();
        s.close();
    }
}
class  Server{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10001);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip+"....connected");

        //读取socket读取流中的数据。
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        //目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。
        PrintWriter out  = new PrintWriter(new FileWriter("F:\\server.mp3"),true);
        String line = null;
        while((line=bufIn.readLine())!=null){
            out.println(line);
        }
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        pw.println("上传成功");
        out.close();
        s.close();
        ss.close();
    }
}
 

 

package com.itheima;
public class Test10 {
    /**
     10、 金额转换,阿拉伯数字转换成中国传统形式。
     *
     * 例如:101000001010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整
     *
     * @param args
     */
    public static void main(String[] args) {
        // 测试
        long L = 101000001010L;
        System.out.println(convert(L));
    }

    public static String convert(long number) {
        // 定义字符数组存储中国数字写法格式
        final char[] chinese = new char[] { '零', '壹', '贰', '叁', '肆', '伍',
                '陆', '柒', '捌', '玖' };
        // 定义字符数组存储中国数字的单位
        final char[] units = new char[] { '圆', '拾', '佰', '仟', '万', '拾', '佰',
                '仟', '亿', '拾', '佰', '仟' };
        // 定义一个字符串缓冲区对字符进行存储
        StringBuilder sb = new StringBuilder();
        int index = 0;
        long lastNumber = 0;
        while (number != 0) {
            lastNumber = number % 10;
            sb.insert(0, units[index++]);
            sb.insert(0, chinese[(int) lastNumber]);
            number = number / 10;
        }
        // 去零操作,通过正则表达式
        return sb.toString().replaceAll("零[拾佰仟]", "零").replaceAll("零+亿", "亿")
                .replaceAll("零{4}万", "零").replaceAll("零+万", "万")
                .replaceAll("零+圆", "圆").replaceAll("零+", "零")
                + "整";
    }
}

posted @ 2014-04-07 19:42  In order to tomorrow  阅读(939)  评论(1编辑  收藏  举报