char,Character,int,字符及編碼日記

char,Character,int,字符及編碼日記

public class Test {
    public static void main(String[] args) {
        char c = 'a';
        Character ch = new Character(c);
        int code = c;
        
        System.out.print(c + " ");//打印出字符
        System.out.print(ch + " ");//打印出字符
        System.out.print(ch.charValue() + " ");//打印出字符
        System.out.println(code);//打印出編碼
    }
}

這個代碼在IDE中編譯運行沒有問題,如果在cmd下,會出錯:編碼GBK的不可映射字符。這個時候在編譯時需要加上-encoding utf-8參數。
如果字符+1,可以變成下一個字符,編碼和字符顯示都是正確的,代碼如下:

public class Test {
    public static void main(String[] args) {
        char a = 'a';
        int code = a;//不需要強制轉換
        char c = (char)(code + 1);//需要強制轉換
        Character ch = new Character(c);
        
        System.out.print(c + " ");//打印出字符
        System.out.print(ch + " ");//打印出字符
        System.out.print(ch.charValue() + " ");//打印出字符
        System.out.println(code);//打印出編碼
    }
}

如果想吧字符‘0’~‘9’加密位新的數字,每位字符+1,比如‘8’變‘9’,‘9’變‘0’,代碼如下:

public class Test {
    public static void main(String[] args) {
        char a = '0';
        int code = a;
        int encode = (code + 1 - 48) % 10 + 48;
        char c = (char)encode;
        
        System.out.print(c + " ");//打印出字符
        System.out.println(encode);//打印出編碼
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章