zoukankan      html  css  js  c++  java
  • Java面试题代码篇

    1.统计字符串中的各种字符的个数并对其排序

    package JavaMianSiTest;
    
    
    
    public class TongJIZiFu {
    
        public static void main(String[] args)  
        {  
            String str = "a12中国3@b&4语*$#@^&言3c";  
      
            String E1 = "[u4e00-u9fa5]";// 中文  
            String E2 = "[a-zA-Z]";// 英文  
            String E3 = "[0-9]";// 数字  
      
            int chineseCount = 0;  
            int englishCount = 0;  
            int numberCount = 0;  
      
            String temp;  
            for (int i = 0; i < str.length(); i++)  
            {  
                temp = String.valueOf(str.charAt(i));  
                if (temp.matches(E1))  
                {  
                    chineseCount++;  
                }  
                if (temp.matches(E2))  
                {  
                    englishCount++;  
                }  
                if (temp.matches(E3))  
                {  
                    numberCount++;  
                }  
            }  
            System.out.println("汉字数:" + chineseCount);  
            System.out.println("英文数:" + englishCount);  
            System.out.println("数字数:" + numberCount);  
            System.out.println("特殊字符:" + (str.length() - (chineseCount + englishCount + numberCount)));  
        }  
    }
    View Code

    2.文件合并

    package JavaMianSiTest;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Reader;
    import java.io.Writer;
    
    /**
     * 1、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
     *
     */
    public class WenjianHebing {
    
    
    public static void main(String[] args) throws IOException {
    
    
    File fileA= new File("D:/eclipse项目/a.txt");
    Reader readerA = new FileReader(fileA); 
    
    //创建可以一次读取一行的输入流
    BufferedReader a = new BufferedReader(readerA);   //一次读取一行,结束符为null
    
    File fileB= new File("D:/eclipse项目/b.txt");
    Reader readerB = new FileReader(fileB); 
    BufferedReader b = new BufferedReader(readerB);   //一次读取一行,结束符为null
    
    String str1=a.readLine();
    
    //用于单词的计数
    int wordsA=0;
    //缓冲区,可以把读取的单词存进去
    StringBuffer bufA= new StringBuffer();
    while(str1!=null){   
    System.out.println("***********"+str1);
    str1=a.readLine();
    wordsA++;
    if(str1!=null)
    bufA.append(str1);
    bufA.append(" ");
    
    }
    System.out.println("a.txt单词数:"+wordsA);
    System.out.println("-------------------------");
    
    String str2=b.readLine();
    int wordsB=0;
    StringBuffer bufB= new StringBuffer();
    while(str2!=null){     
    String[] st = str2.split(" ");  //例如读取的一行为:house home desk
            wordsB+=st.length;
            for(String i :st){
            bufB.append(i);     //把切割后的字符放到b的缓冲区
            bufB.append(" ");
            
            }
    System.out.println(str2);
    str2=b.readLine();
    }
    System.out.println("b.txt单词数:"+wordsB);
    
    System.out.println("A文件:"+bufA);
    System.out.println("B文件:"+bufB);
    
    String strA=bufA.toString();  //转为字符串
    String strB=bufB.toString();
    
    String []A=strA.split(" ");
    String []B=strB.split(" ");
    int total=wordsA+wordsB;
    String [] result=new String [total-1];  //创建一个字符串数组,可以容纳a.txt以及b.txt的单词的总数
    if(wordsA<wordsB)//只做了a文件的单词数比b的少的,后面加个else就可以了
    {
    int j=0;  
    for(int i=0;i<wordsB;i++)
    {
    result[j]=B[i];
    j++;
    if(i<A.length)
    {
    result[j]=A[i];
    j++;
    }
    
    
    
    }
    }
    String content ="";
         for(String x:result){
        content+=x+" "; //把字符数组的内容转为字符串
         }
        System.out.println("content:"+content);
         
      File fileC = new File("D:/eclipse项目/c.txt");
        Writer w = new FileWriter(fileC);
        w.write(content);  //把字符串写到c.txt里去
      
      w.close();     //一定要关闭,不然无法成功的
      
        
    
    
     }
    
    }
    View Code

    3.金额转换

    package JavaMianSiTest;
    /*
     * 金额转换,阿拉伯数字的金额转换成中国传统的形式
     */
    public class RenMingBi {
        public static String convert(double inputMonney) {  
            int decimalDigit = 2;//人名币保留2位小数到分  
            //汉语中数字大写  
            char[] data = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};   
            //汉语中货币单位大写,这样的设计类似于占位符  
            char[] units = {'分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟','兆', '拾', '佰', '仟'};  
            int uint = 0;  
            //在这里我不使用系统函数,自己实现四舍五入,原理:如102.345,保留2位并四舍五入,102.3456->102.3456*10^(2+1)=102345.6->去掉小数部分102345->102345%10=5取到保留小数位数的下一位数字,判断舍入  
            long money = (long)(inputMonney * Math.pow(10, decimalDigit + 1));  
            if (money % 10 > 4) {  
                money = (money / 10) + 1;  
            } else {  
                money = money / 10;  
            }  
            StringBuffer sbf = new StringBuffer();  
            while (money != 0) {  
                sbf.insert(0, units[uint++]);//插入人名币单位  
                sbf.insert(0, data[(int) (money % 10)]);//插入单位所对应的值  
                money = money / 10;  
            }  
            //使用replaceAll替换掉“零+'人民币单位'”,replaceAll里面的old字符串可以是正则表达式  
            return sbf.toString().replaceAll("零[仟佰拾]", "零").replaceAll("零+万", "万").replaceAll("零+亿", "亿").replaceAll("亿万", "亿零").replaceAll("零+", "零").replaceAll("零元", "元").replaceAll("零[角分]", "");  
        }  
        
        public static void main(String[] args) {
            System.out.println(convert(25936.36));
            
        }
    }
    View Code

    4.二叉树

    package JavaMianSiTest;
    
    /** 
     * 说明生活中遇到的二叉树,用 java 实现二叉树 。 
        这是组合设计模式。  
        我有很多个(假设 10 万个)数据要保存起来,以后还需要从保存的这些数据中检索是否存在 
        某个数据, (我想说出二叉树的好处, 该怎么说呢?那就是说别人的缺点) , 假如存在数组中, 
        那么,碰巧要找的数字位于 99999那个地方,那查找的速度将很慢,因为要从第 1 个依次往 67 
        后取,取出来后进行比较。平衡二叉树(构建平衡二叉树需要先排序,我们这里就不作考虑 
        了)可以很好地解决这个问题,但二叉树的遍历(前序,中序,后序)效率要比数组低很多, 
     
     * store(int value)可以选择二叉树中是否可以存在相同的值 
     */  
      
      
      
    //Node,准确的说,是树(包括子树)的根节点  
    public class ErChashuTest{  
        public int value;  
        public ErChashuTest left;  
        public ErChashuTest right;  
        //这种存储方式,是:往已经存在的节点的左右子节点上寻找插入点,而不是考虑作为已经存在的节点的父节点,会造成二叉树的不平衡  
        public void store(int value){  
            if(value<this.value){  
                if(left==null){  
                    left = new ErChashuTest();  
                    left.value=value;  
                }else{  
                    left.store(value);  
                }  
            }else if(value>this.value){  
                if(right==null){  
                    right = new ErChashuTest();  
                    right.value=value;  
                }else{  
                    right.store(value);  
                }  
            }//已经存在的值,不插入  
        }  
        //先序遍历  
        public void preList(){  
            System.out.print(this.value+",");  
            if(left!=null)left.preList();  
            if(right!=null)right.preList();  
        }  
        //中序遍历  
        public void middleList(){  
              
            if(left!=null)left.middleList();  
            System.out.print(this.value+",");  
            if(right!=null)right.middleList();  
        } 
        //后序遍历
        public void afterList(){  
              
            if(left!=null)left.afterList();       
            if(right!=null)right.afterList();  
            System.out.print(this.value+",");  
        }  
          
          
        public static void main(String [] args){  
            int[] data = new int[20];  
            for(int i=0; i<data.length; i++){  
                data[i] = (int)(Math.random()*100)+1;//0+1<<x*100+1<<1*100+1  
                System.out.print(data[i]+",");  
            }  
            System.out.println();  
            ErChashuTest root = new ErChashuTest();  
            root.value = data[0];  
            for(int i=1; i<data.length; i++){  
                root.store(data[i]);  
            }  
            root.preList();  
            System.out.println();  
            root.middleList();  
            System.out.println();  
            root.afterList();  
              
        }  
          
    }  
    View Code

    5.对文件中的姓名的重复次数进行排序

    package JavaMianSiTest;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.TreeSet;
    
    /*
     * 从类试如下文本文件中读取所有的姓名,并打印出重复的姓名和重复的次数
     * 并按重复次数排序
     * 
     */
    
    public class ChongFuSort {
    
        
          /** 
         * ①读取文件到字符串 
         * ②按照换行分割成字符串数组 
         * ③遍历字符串数组,取出姓名 
         * ④将姓名和出现的次数存入map中; 
         * ⑤利用 treeset整理结果;为此需要封装User,其中包含了name,以及count;需要在User 中实现comparable接口或者构造 treesetmap时传入comparator; 
         * 
         * @throws Exception 
         */  
          
        static class User /*implements Comparable<User>*/ {  
             String name;  
              int count ;  
              public User(String name, int count) {  
                  super();  
                  this.name = name;  
                  this.count = count;  
             }  
              @Override  
              public String toString() {  
                  return "User [name=" + name + ", count=" + count + "]" ;  
             }  
               
              /** 
              * 方法一。使用comparable接口来进行排序; 
              */  
    //       @Override  
    //       public int compareTo(User o) {  
    //           if(this.count>o.count)return -1;  
    //           if(this.count<o.count)return 1;  
    //             
    //           return this.name.compareTo(o.name);  
    //             
    //            return this.count>o.count?1:(this.count<o.count?-1:this.name.compareTo(o.name));  
    //             
    //       }  
               
        }  
          
        public static void main(String[] args) throws Exception {  
              //读取文件;  
             File file= new File("D:/eclipse项目/a.txt" );  
             FileReader fr=new FileReader(file);  
              int fileSize=(int) file.length();  
              char[] buff=new char[fileSize];  
               
              //用来存放名字和对应的次数;  
             Map<String, Integer> map= new HashMap<String, Integer>();  
               
              //安装次数由小到大排序后的结果;传入比较器,使用comparator来比较;这样元素再加入的时候就会调用比较方法,按照默认升序排列  
             Set<User> sortedResult= new TreeSet<User>(new Comparator<User>() {  
     
                  public int compare(User o1, User o2) {  
    //                if(o1.count>o2.count)return -1;//默认是从小到大排列  
    //                if(o1.count<o2.count)return 1;  
    //                return o1.name.compareTo(o2.name);  
                       //更简洁的写法  
                       return o1.count >o2.count ? 1:(o1.count<o2.count ?-1:o1.name .compareTo(o2.name));  
                 }  
             });  
               
              int len=fr.read(buff);//得到读取的字符个数;  
             String result= new String(buff,0,len);  
               
             String[] strings = result.split( "\s+");  
              //将姓名提取出来;并将姓名和出现的次数放入到集合中;  
              for (String string : strings) {  
                 string= new String(string.getBytes(),"gbk" );//1,张三,28(解决乱码)  
                 System. out.println(string);  
                   
                 String[] strings2 = string.split( ",");  
                 String name=strings2[0];  
                //存入姓名以及对应的次数  
                 Integer count=map.get(name);  
                  if(count==null ){  
                      map.put(name, 1);  
                 } else{  
                      map.put(name, count+1);  
                 }  
             }  
              //遍历map,得到所有的entry集合,封装成user,加入到set集合中;  
             Set<Map.Entry<String, Integer>> entrySet = map.entrySet();  
             Iterator<Entry<String, Integer>> iterator = entrySet.iterator();  
               
              while(iterator.hasNext()){  
                 Entry<String, Integer> entry = iterator.next();  
                  System. out.println(entry.getKey()+":" +entry.getValue()+"次");  
                 User user= new User(entry.getKey(), entry.getValue());  
                 sortedResult.add(user); //在加入数据时,自动安装 compareto定义的进行排序;  
                   
             }  
              //遍历整理好的set,从小到大升序排列  
             Iterator<User> it = sortedResult.iterator();  
              while(it.hasNext()){  
                 User user=it.next();  
                 System. out.println(user);  
             }  
        }  
    
    }
    View Code

    6.递归排序

    package org.sbj.sort;
    
    import java.util.Arrays;
    
    public class SortTest {
        /*
         * 快速排序(递归排序)
         * @param strDate
         * @param  left
         * @param  right 
         */
        
    public void quickSort(String []strDate,int left,int right ) {
        String middle,tempDate;
        int i,j;
        i=left;
        j=right;
        middle=strDate[(i+j)/2];
        do {
            while (strDate[i].compareTo(middle)<0&&i<right)
                i++;//找出左边比中间值大的数
            while(strDate[j].compareTo(middle)>0&&j>left)
                j--;//找出右边比中间值小的数
            if(i<=j) {//将左边大的数和右边晓得数进行替黄
                tempDate=strDate[i];
                strDate[i]=strDate[j];
                strDate[j]=tempDate;
                i++;
                j--;
            }
            
        }while(i<=j);//当两者交错时停止
        if(i<right) {
            quickSort(strDate,i,right);
            
        }
        if(j>left) {
        quickSort(strDate,left,j);    
        }
    }
        
    public static void main(String[] args) {
        String [] strVoid= {"12","52","36","89","47","12","4","23","68"};
        
        SortTest  sort= new SortTest();
        sort.quickSort(strVoid, 0, strVoid.length-1);
        for(int i=0;i<strVoid.length;i++) {
            System.out.print(strVoid[i]+" ");
        }
    }
    }
    View Code
  • 相关阅读:
    数据库总结
    数据库 查询方法详解 以学生老师信息表为例
    SQL 常与LIKE关键字配合使用,表示一个模糊的范围 。
    SQL 数据类型
    十分钟搞清字符集和字符编码
    c# 集合
    c# 开根号 牛顿迭代
    c# 打名字
    转 揭开计算机的神秘面纱 来源:吴广磊的博客
    c# while穷举(凑钱)
  • 原文地址:https://www.cnblogs.com/sbj-dawn/p/7825935.html
Copyright © 2011-2022 走看看