java日常练手(面试)小示例

在这里整理一些日常用来练手或者面试时的小示例


1. 利用 StringBuffer 或者 StringBuilder 的reverse 实现 字符串反转

实现代码

 public static String stringReverse(String string) {
        return new StringBuffer(string).reverse().toString();
    }


 2. 打印一个九九乘法表

public static void multiplication() {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i + " x " + j + " = " + i * j +"   ");
            }
            System.out.println();
        }
    }


 3. 读取文件 
// File file = new File("D:/work/xxxx.txt");
 

public static String InputStreamReader(File file) {
        String string = "";

        try {
            // 读取文件内容 (输入流)
            FileInputStream out = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(out);
            int ch = 0;
            while ((ch = isr.read()) != -1) {
                string += ((char) ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }

 4. 汉字转拼音

public static String toHanYuPinyinString(String str) {
        String pinyin = "";
        try {
            HanyuPinyinOutputFormat fmt = new HanyuPinyinOutputFormat();
            fmt.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            String pinyin1 = PinyinHelper.toHanYuPinyinString(str + ":", fmt, "_", false);
            pinyin = pinyin1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pinyin;
    }

5.冒牌排序

 public static void bubbleSort() {
        int a[] = {99, 3, 9, 5, 0, 8, 2, 11, 4, 54, 43, 32};

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j + 1];
                    a[j + 1] = a[j];
                    a[j] = temp;
                }
            }
        }
       System.out.println(Arrays.toString(a));
    }

6.二分查找(前提是数组是有序的)

public static int biSearch(int x) {
        int a[] = {0, 1, 2, 3, 4, 5, 6};

        int start = 0;
        int end = a.length-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (a[mid] == x) {
                return mid;
            } else if (a[mid] > x) {
                end = mid;
            } else if (a[mid] < x) {
                start = mid;
            }
        }

        return -1;
    }

 

你可能感兴趣的:(java)