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;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值