【问题标题】:How can I print unicode symbols within a certain range?如何打印一定范围内的 unicode 符号?
【发布时间】:2017-05-12 03:12:22
【问题描述】:

我正在尝试制作一个打印所有 Unicode 符号 \u6000 到 \u7000(1000 个符号)的程序。我的程序打印 50 个字符,开始一个新行,再打印 50 个,等等(没有问题)。

我知道如何打印 Unicode 符号,但我不确定如何增量打印(每次加 1)。这是我的程序:

public class UnicodePrinter {
    public static void main(String args[]) {
        for (int i = 6000; i<7000; i++) {
            if(i%50 == 0) {
                System.out.println();
            }
            System.out.print("\u"+i); //issue here, see below
        }
    }
}

我的打印语句出现错误,我在其中输入了 "\u"+i 说“无效的 unicode”,因为 \u 没有用数字完成,但我不知道如何解决它。

【问题讨论】:

    标签: java for-loop unicode


    【解决方案1】:

    直接生成chars,像这样:

    public class UnicodePrinter {
        public static void main(String args[])
        {
            for (char i = '\u6000'; i < '\u7000'; i++) {
                if (i % 50 == 0) {
                    System.out.println();
                }
                System.out.print(i); //issue here, see below
            }
        }
    }
    

    【讨论】:

    • 这实际上是正确的答案,只有一个缺陷是循环中使用的值
    • 代码的一个问题可能是您的控制台字体不支持所需的 unicode 字符。在这种情况下,您可以将字符打印到(UTF-8 编码)文件中
    • @KevinAnderson 答案很好,也很简单。我不知道我可以在for 循环中使用char。感谢您的回答!
    • 可以在循环中使用 char,但除非必要,否则必须避免使用,因为它不能存储 -ve 值,这就是为什么会有 'short' 类型。
    【解决方案2】:

    将其转换为十六进制后将其转换为字符:

    for (int i = 6000; i<7000; i++) {
        if(i%50 == 0) {
            System.out.println();
        }
        char c = (char) Integer.parseInt(String.valueOf(i), 16);
        System.out.print(c);
    }
    

    【讨论】:

    • 我没有投反对票,但我尝试运行您的代码,它只打印问号。
    • 我得到相同的输出 - 那些不是正确的字符。我们检查了它:System.out.println("\u6000"); 我认为这个输出是正确的。
    • 哎呀,我的错。没错,谢谢你的回答
    • 没问题。很高兴我能帮上忙。
    • 很多方面都是错的。最明显的一个:\u6000\u7000 之间有多少个代码点?还有,你打印了多少?
    猜你喜欢
    • 2013-04-15
    • 2011-04-15
    • 2021-12-28
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多