Eclipse console not printing Chinese characters

时光毁灭记忆、已成空白 提交于 2021-02-04 21:39:56

问题


I have written a Java function which take a string parameter and generate a random id from it using some logic. Everything is working fine if my String contains English characters but when I pass Chinese characters, these are replaced by ???

Here is my code:

public static String generateId(String inputString) {
        /**
         * Split input string on the basis of white spaces
         */
        String arr[] = inputString.split(" ");
        /**
         * Change the first character of first substring to lowercase
         */
        String id = arr[0].substring(0, 1).toLowerCase() + arr[0].substring(1);
        if(arr.length > 1)
        {
        for (int i = 1; i < arr.length; i++) {
            /**
             * Change the first character of remaining substrings to uppercase
             * and append to id
             */
            if(arr[i].trim().length() != 0)
            {
                id = id + arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1);
            }
        }
        }
        int length = id.length();
        Random random = new Random();
        /**
         * If the length of id is less than 8 then append random digits to make
         * length equals to 8 else take a substring of length equals to 8
         */
        if (length < 8) {
            int len = 8 - length;
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < len; i++) {
                sb.append((char) ('0' + random.nextInt(10)));
            }
            id = id + sb;

        } else {
            id = id.substring(0, 8);
        }
        /**
         * Append 4 digits random number to make length of id equals to 12
         * characters long
         */
        return id + String.format("%04d", random.nextInt(10000));
    }

Here are my outputs for different cases:

 System.out.println(MyClass.generateId("anyid"));

Output: anyid0660920

System.out.println(MyClass.generateId("这是标题"));

Output: ????14102367

how can I deal with this issue?


回答1:


Change the Console encoding to UTF-8,

Go to Run -> Run Configurations -> Common Tab -> Console Encoding (or just Encoding, in newer versions) -> Choose UTF - 8.

By default it'd be Latin encoding (8859) which doesn't support Chinese.



来源:https://stackoverflow.com/questions/50370883/eclipse-console-not-printing-chinese-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!