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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章