算法面试题

来源:互联网 发布:cad绘图软件 编辑:程序博客网 时间:2024/06/10 14:48
1. 用递归实现字符串倒转
1. public class StringReverse {
2.    public static String reverse(String originStr) {
3.        if (originStr == null || originStr.length() == 1) {
4.            return originStr;
5.        }
6.        return reverse(originStr.substring(1)) + originStr.charAt(0);
7.    }
8.    public static void main(String[] args) {
9.        System.out.println(reverse("hello"));
10.    }
11. }


2. 打印如下图案
    1
 1 2 1
1 2 4  2 1
....
代码如下:改变N的值就可以改变行数
1. private static void test02(int n) {
2. for (int i = 0; i < n; i++) {
3. // 输出前面的空格
4. for (int j = 0; j < n - i - 1; j++) {
5. System.out.print("\t");
6. }
7. // 输出数字内容
8. for (int j = 0; j <= i; j++) {
9. System.out.print("\t"
10. + Double.valueOf(Math.pow(2, j)).intValue());
11. }
12. for (int j = i - 1; j >= 0; j--) {
13. System.out.print("\t"
14. + Double.valueOf(Math.pow(2, j)).intValue());
15. }
16. // 输出后面的空格
17. /*
18. * for (int j = 0; j < (Math.pow(2, n - 1 - i) - Math.pow(2, i)) /
19. * 2; j++) { System.out.print("\t"); }
20. */
21. System.out.println();
22. }
23. }


3. 模拟实现LinkedList
1. package com.wenfeng.javase;
2.
3. import java.util.Iterator;
4.
5. /**
6. * 模拟实现LinkedList
7. *
8. */
9. public class MyLinkedList<E> implements Iterable<E> {
10. int size;
11. private Node head;
12. private Node tail;
13. public void add(E e){
14. Node node = new Node(e,null);
15. if(head==null){
16. head = node;
17. tail = node;
18. }else{
19. tail.setNext(node);
20. tail = node;
21. }
22. size++;
23. }
24. public int getSize(){
25. return size;
26. }
27.
28. public Iterator<E> iterator() {  
29.    return new Iterator<E>(){  
30.        Node temp=head;  
31.        public boolean hasNext() {  
32.            return temp!=null;  
33.        }  
34.
35.        public E next() {  
36.            E data=temp.data;  
37.            temp=temp.next;  
38.            return data;  
39.        }  
40.
41.        public void remove() {  
42.              
43.        }};  
44. }  
45.
46. class Node{
47. private E data;
48. private Node next;
49. public Node(E data,Node next){
50. this.data = data;
51. this.next = next;
52.
53. }
54. public void setData(E data){
55. this.data = data;
56. }
57. public E getData(){
58. return data;
59. }
60. public void setNext(Node next){
61. this.next = next;
62. }
63. public Node getNext(){
64. return next;
65. }
66. }
67. }


4. 将一个正整数分解质因数。例如输入90,打印出90=2*3*3*5
1. //将一个正整数分解质因数。例如输入90,打印出90=2*3*3*5
2. public class Test05 {
3. public static void main(String[] args) {
4. decompose(90);
5. }
6. private static void decompose(int n){
7. System.out.print(n+"=");
8. int m = n;
9. for(int i=2;i<m;i++){
10. while(n%i==0 && n!=i){
11. n/=i;
12. System.out.print(i+"*");
13. }if(n==i){
14. System.out.println(i);
15. break;
16. }
17. }
18. }
19. }


5. 输入两个正整数m和求其最大公约数和最小公倍数
1. /**
2. * 输入两个正整数m和n求其最大公约数和最小公倍数
3. *
4. */
5.
6. public class Max_min{
7. public static void main(String[] args){
8. int m = 6;
9. int n = 8;
10. int yshu;
11. int bshu;
12. int max = m>n?m:n;
13. int min = m<n?m:n;
14. while(max%min!=0){
15. int temp = max%min;
16. max = min;
17. min = temp;
18.
19. yshu = min;
20. bshu = (m*n)/min;
21. System.out.println("最大公约数:"+yshu);
22. System.out.println("最小公倍数:"+bshu);
23. }
24. }


6. 请设计一个一百亿的计算器
首先要明白这道题目的考查点是什么,一是大家首先要对计算机原理的底层细节要清楚、要知道加减法的位运算原理和知道计算机中的算术运算会发生越界的情况, 二是要具备一定的面向对象的设计思想。首先,计算机中用固定数量的几个字节来存储的数值,所以计算机中能够表示的数值是有一定的范围的, 为了便于讲解和理解,我们先以byte 类型的整数为例,它用1个字节进行存储,表示的最大数值范围为-128到+127。-1在内存中对应的二进制数据为11111111, 如果两个-1相加,不考虑Java运算时的类型提升,运算后会产生进位,二进制结果为1,11111110,由于进位后超过了byte类型的存储空间,所以进位部分被舍弃, 即最终的结果为11111110,也就是-2,这正好利用溢位的方式实现了负数的运算。-128在内存中对应的二进制数据为10000000,如果两个-128相加, 不考虑Java运算时的类型提升,运算后会产生进位,二进制结果为1,00000000,由于进位后超过了byte类型的存储空间,所以进位部分被舍弃, 即最终的结果为00000000,也就是0,这样的结果显然不是我们期望的,这说明计算机中的算术运算是会发生越界情况的, 两个数值的运算结果不能超过计算机中的该类型的数值范围。由于Java中涉及表达式运算时的类型自动提升, 我们无法用byte类型来做演示这种问题和现象的实验,大家可以用下面一个使用整数做实验的例子程序体验一下:
1. int a = Integer.MAX_VALUE;
2.   int b = Integer.MAX_VALUE;
3.   int sum = a + b;
4.   System.out.println(“a=”+a+”,b=”+b+”,sum=”+sum);
  先不考虑long类型,由于int的正数范围为2的31次方,表示的最大数值约等于210001000*1000,也就是20亿的大小,所以,要实现一个一百亿的计算器, 我们得自己设计一个类可以用于表示很大的整数,并且提供了与另外一个整数进行加减乘除的功能,大概功能如下:
  ()这个类内部有两个成员变量,一个表示符号,另一个用字节数组表示数值的二进制数
  ()有一个构造方法,把一个包含有多位数值的字符串转换到内部的符号和字节数组中
  ()提供加减乘除的功能
1. public class BigInteger {
2.   int sign;
3.   byte[] val;
4.   public Biginteger(String val) {
5.   sign = ;
6.   val = ;
7.   }
8.   public BigInteger add(BigInteger other) {
9.   }
10.   public BigInteger subtract(BigInteger other) {
11.   }
12.   public BigInteger multiply(BigInteger other) {
13.   }
14.   public BigInteger divide(BigInteger other) {
15.   }
16.   
  备注:要想写出这个类的完整代码,是非常复杂的,如果有兴趣的话,可以参看jdk中自带的java.math.BigInteger类的源码。 面试的人也知道谁都不可能在短时间内写出这个类的完整代码的,他要的是你是否有这方面的概念和意识,他最重要的还是考查你的能力, 所以,你不要因为自己无法写出完整的最终结果就放弃答这道题,你要做的就是你比别人写得多,证明你比别人强,你有这方面的思想意识就可以了, 毕竟别人可能连题目的意思都看不懂,什么都没写,你要敢于答这道题,即使只答了一部分,那也与那些什么都不懂的人区别出来,拉开了距离,算是矮子中的高个, 机会当然就属于你了。另外,答案中的框架代码也很重要,体现了一些面向对象设计的功底,特别是其中的方法命名很专业,用的英文单词很精准, 这也是能力、经验、专业性、英语水平等多个方面的体现,会给人留下很好的印象,在编程能力和其他方面条件差不多的情况下,英语好除了可以使你获得更多机会外, 薪水可以高出一千元。
7. 排序都有哪几种方法?请列举用。JAVA实现一个快速排序。
 http://blog.csdn.net/qy1387/article/details/7752973
8. 给一个数组,其中有一个重复元素占半数以上,找出这个元素。
1. public class FindMost {  
2.   
3.   public static <T> T find(T[] x){  
4.      T temp = null;  
5.      for(int i = 0, nTimes = 0; i< x.length;i++) {  
6.          if(nTimes == 0) {  
7.              temp= x[i];  
8.              nTimes= 1;  
9.          }  
10.          else {  
11.              if(x[i].equals(temp)) {  
12.                  nTimes++;  
13.              }  
14.              else {  
15.                  nTimes--;  
16.              }  
17.          }  
18.      }  
19.      return temp;  
20.   }  
21.    
22.   public static void main(String[] args) {  
23.      String[]strs = {"hello","kiss","hello","hello","maybe"};  
24.      System.out.println(find(strs));  
25.   }  
26. }  


9. 有一个已经排好序的整数数组,其中存在重复元素,请将重复元素删除掉,例如,A= [1, 1, 2, 2, 3],处理之后的数组应当为A= [1, 2, 3]。
1. public class RemoveDuplication {
2. public static int[] removeDuplicates(int a[]) {
3. if (a.length <= 1) {
4. return a;
5. }
6. int index = 0;
7. for (int i = 1; i < a.length; i++) {
8. if (a[index] != a[i]) {
9. a[++index] = a[i];
10. }
11. }
12. int[] b = new int[index + 1];
13. System.arraycopy(a, 0, b, 0, b.length);
14. return b;
15. }
16.
17. public static void main(String[] args) {
18. int[] a = { 1, 1, 2, 2, 3 };
19. a = removeDuplicates(a);
20. System.out.println(Arrays.toString(a));
21. }
22. }


10. 写一个算法判断一个英文单词的所有字母是否全都不同(不区分大小写)
1. public class AllNotTheSame{
2. public static void main(String[] args){
3. System.out.println(judge("hello"));
4. System.out.println(judge("simple"));
5. }
6.
7. private static boolean judge(String str){
8. String temp = str.toLowerCase();
9. int[] letterCounter = new int[26];
10. for(int i=0;i<temp.length();i++){
11. int index = temp.charAt(i)-'a';
12. letterCounter[index]++;
13. if(letterCounter[index]>1){
14. return false;
15. }
16. }
17.
18. return true;
19. }
20. }


11. 一个有n级的台阶,一次可以走1级、2级或3级,问走完n级台阶有多少种走法。
1. public class GoSteps{
2. public static void main(String[] args){
3. System.out.println(countWays(10));
4. }
5. private static int countWays(int n){
6. int step = 0;
7. if(n<0){
8. step = 0;
9. }
10. if(n==0){
11. step = 2;
12. }
13. if(n>=3){
14. step = countWays(n-1)+countWays(n-2)+countWays(n-3);
15. }
16. return step;
17. }
18. }


12. 对于一个有N个整数元素的一维数组,找出它的子数组(数组中下标连续的元素组成的数组)之和的最大值。
1. //可以使用动态规划的思想求解:
2. public class MaxSum {
3. private static int max(int x, int y) {
4. return x > y ? x : y;
5. }
6.
7. public static int maxSum(int[] array) {
8. int n = array.length;
9. int[] start = new int[n];
10. int[] all = new int[n];
11. all[n - 1] = start[n - 1] = array[n - 1];
12. for (int i = n - 2; i >= 0; i--) {
13. start[i] = max(array[i], array[i] + start[i + 1]);
14. all[i] = max(start[i], all[i + 1]);
15. }
16. return all[0];
17. }
18.
19. public static void main(String[] args) {
20. int[] x1 = { 1, -2, 3, 5, -3, 2 };
21. int[] x2 = { 0, -2, 3, 5, -1, 2 };
22. int[] x3 = { -9, -2, -3, -5, -3 };
23. System.out.println(maxSum(x1)); // 8
24. System.out.println(maxSum(x2)); // 9
25. System.out.println(maxSum(x3)); // -2
26. }
27. }


13. 全排列:给出五个数字12345的所有排列。
1. public class FullPermutation {
2. public static void perm(int[] list) {
3. perm(list, 0);
4. }
5.
6. private static void perm(int[] list, int k) {
7. if (k == list.length) {
8. for (int i = 0; i < list.length; i++) {
9. System.out.print(list[i]);
10. }
11. System.out.println();
12. } else {
13. for (int i = k; i < list.length; i++) {
14. swap(list, k, i);
15. perm(list, k + 1);
16. swap(list, k, i);
17. }
18. }
19. }
20.
21. private static void swap(int[] list, int pos1, int pos2) {
22. int temp = list[pos1];
23. list[pos1] = list[pos2];
24. list[pos2] = temp;
25. }
26.
27. public static void main(String[] args) {
28. int[] x = { 1, 2, 3, 4, 5 };
29. perm(x);
30. }
31. }


14. 回文素数:所谓回文数就是顺着读和倒着读一样的数(例如:11,121,1991…),回文素数就是既是回文数又是素数(只能被1和自身整除的数)的数。编程找出11~9999之间的回文素数。
1. public class PalindromicPrimeNumber {
2. public static void main(String[] args) {
3. for (int i = 11; i < 10000; i++) {
4. if (isPrime(i) && isPalindromic(i)) {
5. System.out.println(i);
6. }
7. }
8. }
9. private static boolean isPrime(int n) {
10. for (int i = 2; i <= Math.sqrt(n); i++) {
11. if (n % i == 0) {
12. return false;
13. }
14. }
15. return true;
16. }
17. private static boolean isPalindromic(int n) {
18. int temp = n;
19. int sum = 0;
20. while (temp != 0) {
21. sum = 10 * sum + temp % 10;
22. temp /= 10;
23. }
24. return sum == n;
25. }
26. }


15. 约瑟夫环:15个基督教徒和15个非教徒在海上遇险,必须将其中一半的人投入海中,其余的人才能幸免于难,于是30个人围成一圈,从某一个人开始从1报数,报到9的人就扔进大海,他后面的人继续从1开始报数,重复上面的规则,直到剩下15个人为止。结果由于上帝的保佑,15个基督教徒最后都幸免于难,问原来这些人是怎么排列的,哪些位置是基督教徒,哪些位置是非教徒。
1. public class Josephu {
2. private static final int DEAD_NUM = 9;
3.
4. public static void main(String[] args) {
5. boolean[] persons = new boolean[30];
6. for (int i = 0; i < persons.length; i++) {
7. persons[i] = true;
8. }
9. int counter = 0;
10. int claimNumber = 0;
11. int index = 0;
12. while (counter < 15) {
13. if (persons[index]) {
14. claimNumber++;
15. if (claimNumber == DEAD_NUM) {
16. counter++;
17. claimNumber = 0;
18. persons[index] = false;
19. }
20. }
21. index++;
22. if (index >= persons.length) {
23. index = 0;
24. }
25. }
26. for (boolean p : persons) {
27. if (p) {
28. System.out.print("基");
29. } else {
30. System.out.print("非");
31. }
32. }
33. }
34. }


16. Java 的通信编程,编程题(或问答),用JAVA SOCKET编程,读服务器几个字符,再写入本地显示?
1. 服务端
1. public class Client { 
2. Socket socket;
3. BufferedReader in;
4. PrintWriter out;
5.
6. public Client() {
7. try {
8. System.out.println("Try to Connect to 127.0.0.1:10000");
9. socket = new Socket("127.0.0.1",10000);
10. System.out.println("The Server Connected!");
11. System.out.println("Please enter some Character:");
12. BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
13. out = new PrintWriter(socket.getOutputStream(),true);
14. out.println(line.readLine());
15.
16. in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
17. System.out.println(in.readLine());
18. in.close();
19. line.close();
20. out.close();
21.
22. } catch (IOException e) {
23. out.println("Wrong");
24. }
25. }
26. }


客户端:
1. public class Server { 
2.    private ServerSocket ss;
3.    private BufferedReader in;
4.    private PrintWriter out;
5.    Socket socket;
6.    
7.    public Server(){
8.        try {
9.            ss = new ServerSocket(10000);
10.            while(true){
11.                socket = ss.accept();
12.                String remoteIp = socket.getInetAddress().getHostAddress();
13.                String remotePort = ":"+socket.getLocalPort();
14.                System.out.println("A client come in!IP:" + remoteIp
15.                        + remotePort);
16.                
17.                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
18.                String line = in.readLine();
19.                System.out.println(line);
20.                
21.                out = new PrintWriter(socket.getOutputStream(),true);
22.                out.println("Your Message Received!");
23.                in.close();out.close();
24.                socket.close();
25.            }
26.        } catch (IOException e) {
27.            out.println("wrong");
28.        }
29.    }
30.


 
http://www.voidcn.com/blog/hao947_hao947/article/p-4523092.html
17. 从键盘读取若干个数,以“-1”结束,按从小到大的顺序排序。
1. public class sc_num {
2. public static void main(String[] args) {
3. Scanner scanner = new Scanner(System.in);
4. int scnum = 0;
5. int i = 0;
6. int[] scarry = new int[30];
7. System.out.println("????(-1??):");
8. while (scnum != -1) {
9. scarry[i] = scanner.nextInt();
10. ;
11. scnum = scarry[i];
12. i++;
13. }
14. xuanZe(scarry, i - 1);
15. }
16.
17. // ????
18. public static void xuanZe(int[] x, int n) {
19. for (int i = 0; i < n; i++) {
20. int lowerIndex = i;
21. for (int j = i + 1; j < n; j++) {
22. if (x[j] < x[lowerIndex]) {
23. lowerIndex = j;
24. }
25. }
26. int temp = x[i];
27. x[i] = x[lowerIndex];
28. x[lowerIndex] = temp;
29. }
30. for (int i = 0; i < n; i++) {
31. System.out.print(x[i] + " ");
32. }
33. }
34. }


18. 从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:
http://blog.csdn.net/yongzhian/article/details/38854197
19. 说明生活中遇到的二叉树,用java实现二叉树
1. /**
2. * 说明生活中遇到的二叉树,用 java 实现二叉树 。 这是组合设计模式。 我有很多个(假设 10
3. * 万个)数据要保存起来,以后还需要从保存的这些数据中检索是否存在 某个数据, (我想说出二叉树的好处, 该怎么说呢?那就是说别人的缺点) ,
4. * 假如存在数组中, 那么,碰巧要找的数字位于 99999那个地方,那查找的速度将很慢,因为要从第 1 个依次往 67
5. * 后取,取出来后进行比较。平衡二叉树(构建平衡二叉树需要先排序,我们这里就不作考虑
6. * 了)可以很好地解决这个问题,但二叉树的遍历(前序,中序,后序)效率要比数组低很多,
7.
8. * store(int value)可以选择二叉树中是否可以存在相同的值
9. */
10.
11. // Node,准确的说,是树(包括子树)的根节点
12. public class Node {
13. public int value;
14. public Node left;
15. public Node right;
16.
17. // 这种存储方式,是:往已经存在的节点的左右子节点上寻找插入点,而不是考虑作为已经存在的节点的父节点,会造成二叉树的不平衡
18. public void store(int value) {
19. if (value < this.value) {
20. if (left == null) {
21. left = new Node();
22. left.value = value;
23. } else {
24. left.store(value);
25. }
26. } else if (value > this.value) {
27. if (right == null) {
28. right = new Node();
29. right.value = value;
30. } else {
31. right.store(value);
32. }
33. }// 已经存在的值,不插入
34. }
35.
36. // 先序遍历
37. public void preList() {
38. System.out.print(this.value + ",");
39. if (left != null)
40. left.preList();
41. if (right != null)
42. right.preList();
43. }
44.
45. // 中序遍历
46. public void middleList() {
47.
48. if (left != null)
49. left.middleList();
50. System.out.print(this.value + ",");
51. if (right != null)
52. right.middleList();
53. }
54.
55. public void afterList() {
56.
57. if (left != null)
58. left.afterList();
59. if (right != null)
60. right.afterList();
61. System.out.print(this.value + ",");
62. }
63.
64. public static void main(String[] args) {
65. int[] data = new int[20];
66. for (int i = 0; i < data.length; i++) {
67. data[i] = (int) (Math.random() * 100) + 1;// 0+1<<x*100+1<<1*100+1
68. System.out.print(data[i] + ",");
69. }
70. System.out.println();
71. Node root = new Node();
72. root.value = data[0];
73. for (int i = 1; i < data.length; i++) {
74. root.store(data[i]);
75. }
76. root.preList();
77. System.out.println();
78. root.middleList();
79. System.out.println();
80. root.afterList();
81.
82. }
83. }




http://www.programgo.com/article/975972978/
20. 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。
1. public class CountChar {
2. public static String readChar(String str, int n) {
3. byte[] orignal = str.getBytes();
4. String changeStr = "";
5. // 判断orignal[n]是否是负数,如果为负数的话就表示此为中文字符
6. if (orignal[n] < 0)
7. // 构造函数new String(byte[] bytes, int offset, int length);
8. changeStr = new String(orignal, 0, --n);
9. else
10. changeStr = new String(orignal, 0, n);
11. return changeStr;
12. }
13.
14. public static void main(String[] args) {
15. String str = "我ABC汉DEF";
16. int number = 7;
17. // System.out.println(readChar(str, number));
18. System.out.println(readChar(str, number));
19. }
20. }


21. 编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad。
1. /**
2. * 编写一个程序,将 d:\java目录下的所有.java文件复制到
3. * d:\jad目录下,并将原来文件的扩展名从.java改为.jad。
4. */
5. public class CopyFile {
6. public static void main(String[] args) throws Exception {
7. // 在D盘找到java文件夹
8. File srcDir = new File("D:\\java");
9. if (!(srcDir.exists() && srcDir.isDirectory()))
10. throw new Exception("目录不存在");
11. // 列出java文件夹下的所有以.java结尾的文件
12. File[] files = srcDir.listFiles(new FilenameFilter() {
13. public boolean accept(File dir, String name) {
14. return name.endsWith(".java");
15. }
16. });
17. System.out.println(files.length);
18. // 判断jad目录是否存在,不存在创建目录
19. File destDir = new File("d:\\jad");
20. if (!destDir.exists())
21. destDir.mkdir();
22. // 把.java文件变成.jad文件
23. for (File f : files) {
24. FileInputStream fis = new FileInputStream(f);
25. String destFileName = f.getName().replaceAll("\\.java$", ".jad");
26. FileOutputStream fos = new FileOutputStream(new File(destDir,
27. destFileName));
28. copy(fis, fos);
29. fis.close();
30. fos.close();
31. }
32. }
33.
34. private static void copy(InputStream ips, OutputStream ops)
35. throws Exception {
36. int len = 0;
37. byte[] buf = new byte[1024];
38. while ((len = ips.read(buf)) != -1) {
39. ops.write(buf, 0, len);
40. }
41. }
42. }




http://913061291.blog.51cto.com/3367346/1301079
22. 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
1. public class Test{  
2.    public static void main(String [] args) throws Exception{  
3.        FileWriter ra = new FileWriter("a.txt");//字符流  
4.        ra.write("adsf\nasgdg\ndasg\nqewr\ntrt\n");  
5.        ra.close();  
6.          
7.        FileWriter rb = new FileWriter("b.txt");  
8.        rb.write("adsf asgdg dasg\nqewr trt\n");  
9.        rb.close();  
10.          
11.        FileManager a = new FileManager("a.txt", new char[]{'\n'});  
12.        FileManager b = new FileManager("b.txt", new char[]{'\n',' '});  
13.        FileWriter c = new FileWriter("c.txt");  
14.        String aWord = null;  
15.        String bWord = null;  
16.        //交替写入  
17.        while((aWord=a.nextWord())!=null){  
18.            c.write(aWord+"\n");  
19.            bWord = b.nextWord();  
20.            if(bWord!=null){  
21.                c.write(bWord+"\n");  
22.            }             
23.        }  
24.        //如果b还有  
25.        while((bWord=b.nextWord())!=null){  
26.            c.write(bWord+"\n");  
27.        }  
28.        c.close();  
29.    }  
30. }  
31.  
32. class FileManager{  
33.    String[] words = null;//  
34.    int pos = 0;//words的索引  
35.    /** 
36.     * 读入文件信息,根据分隔符,存入字符串数组words中  
37.     * @param filename 
38.     * @param seperators 
39.     * @throws Exception 
40.     */  
41.    public FileManager(String filename, char[] seperators) throws Exception{  
42.        File f = new File(filename);  
43.        FileReader reader = new FileReader(filename);//文件字符流  
44.        char[] buf = new char[(int)f.length()];//f和文件字符流一样大  
45.        int len = reader.read(buf);//读取的长度---小文件,一次性读取  
46.        String results = new String(buf,0,len);  
47.        String regex = null;//正则表达式  
48.        if(seperators.length>1){  
49.            regex=""+seperators[0]+"|"+seperators[1];  
50.        }  
51.        else{  
52.            regex=""+seperators[0];           
53.        }  
54.        words=results.split(regex);  
55.        reader.close();  
56.    }  
57.    /** 
58.     * 返回当前pos位置的words[pos],然后后移pos,即pos++ 
59.     * @return 
60.     */  
61.    public String nextWord(){  
62.        if(pos==words.length){  
63.            return null;  
64.        }  
65.        return words[pos++];          
66.    }  
67. }  




http://www.programgo.com/article/850772954/
23. 子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。
1. /**
2. * 子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。
3.
4. * @author lijinnan
5. * @date:2013-11-5 下午3:07:10
6. */
7. public class ThreadComunication {
8. private static final int ROUND_COUNT = 50;
9.
10. public static void main(String[] args) {
11. // 主线程和子线程“共享”一个Busines实例
12. final Business business = new Business();
13. /*
14. * //主线程 for (int i = 0; i < ROUND_COUNT; i++) { business.main(i); }
15. */
16. // 子线程-注意要先启动子线程,否则子线程不会启动,主线程在roundIndex=0执行完毕后就陷入无限等待
17. new Thread(new Runnable() {
18. @Override
19. public void run() {
20. for (int i = 0; i < ROUND_COUNT; i++) {
21. business.sub(i);
22. }
23. }
24.
25. }).start();
26. // 主线程
27. for (int i = 0; i < ROUND_COUNT; i++) {
28. business.main(i);
29. }
30. }
31.
32. }
33.
34. class Business {
35. private static final int SUB_COUNT = 10;
36. private static final int MAIN_COUNT = 100;
37. private boolean doSub;
38.
39. public synchronized void sub(int roundIndex) {
40. while (!doSub) {
41. try {
42. wait();
43. } catch (InterruptedException e) {
44. // ignore
45. }
46. }
47. for (int i = 0; i < SUB_COUNT; i++) {
48. System.out.println("sub " + i + " of " + roundIndex);
49. }
50. doSub = false;
51. notifyAll();
52. }
53.
54. public synchronized void main(int roundIndex) {
55. while (doSub) {
56. try {
57. wait();
58. } catch (InterruptedException e) {
59. // ignore
60. }
61. }
62. for (int i = 0; i < MAIN_COUNT; i++) {
63. System.out.println("main " + i + " of " + roundIndex);
64. }
65. doSub = true;
66. notifyAll();
67. }
68. }


http://bylijinnan.iteye.com/blog/1971757
24. 判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日。
1. public class RegexTest {
2. public static void main(String[] args) {
3. // 测试是否为合法的身份证号码
4. String[] strs = { "130681198712092019", "13068119871209201x",
5. "13068119871209201", "123456789012345", "12345678901234x",
6. "1234567890123" };
7. Pattern p1 = Pattern.compile("\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z]");
8. for (int i = 0; i < strs.length; i++) {
9. Matcher matcher = p1.matcher(strs[i]);
10. System.out.println(strs[i] + ":" + matcher.matches());
11. }
12. Pattern p2 = Pattern.compile("\\d{6}(\\d{8}).*"); // 用于提取出生日字符串
13. Pattern p3 = Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");// 用于将生日字符串进行分解为年月日
14. for (int i = 0; i < strs.length; i++) {
15. Matcher matcher = p2.matcher(strs[i]);
16. boolean b = matcher.find();
17. if (b) {
18. String s = matcher.group(1);
19. Matcher matcher2 = p3.matcher(s);
20. if (matcher2.find()) {
21. System.out
22. .println("生日为" + matcher2.group(1) + "年"
23. + matcher2.group(2) + "月"
24. + matcher2.group(3) + "日");
25. }
26. }
27. }
28. }
29. }

0 0
原创粉丝点击