【问题标题】:Why do I get Chinese characters when generating random numbers in Java?java生成随机数时为什么会得到汉字?
【发布时间】:2016-08-19 15:07:12
【问题描述】:

该程序生成 50 个介于 1 到 100 之间的随机数,并将输出写入 fileresult.txt 中。

    FileWriter outputChar = new FileWriter(new File ("fileresult.txt"));
    Random random = new Random();
    for(int i = 1 ; i <= 50 ; i++){
        int min = 1;
        int max = 100;
        int number = random.nextInt(max - min + 1) + min;
        outputChar.write(number);
    }
    outputChar.close();

问题是输出的不是整数值,而是很多汉字。为什么会这样?

【问题讨论】:

  • 您正在写入原始字节,如果您想要 ascii 整数值,请使用 PrintStream
  • @ElliottFrisch 或使用outputChar.write(String.valueOf(number) + "\n"); 进行最少的重写。
  • @ElliottFrisch 实际上我正在使用 char-stream 和 byte-stream 进行比较。上面的代码用于 char-stream 部分。仅供参考,我还得到了奇怪的字符作为输出字节流部分。我希望您能详细说明 char 流和字节流,以及它们与 ascii 值和原始字节的关系......我有点难以理解这个概念。

标签: java random filewriter


【解决方案1】:

它将chars 写入1-100 范围内的输出,这是Unicode ASCII 范围内的UTF-16 字符,但31 是控制码。 FileWriter 将使用平台默认字符集从 Unicode 转换。我猜它是 Big5 字符集之一。

Path path = Paths.get("fileresult");
try (Writer outputChar = Files.newBufferedWriter(path, StandardCharsets.US_ASCII)) {
    // Or UTF_8.
    Random random = new Random();
    for (int i = 1 ; i <= 50 ; i++){
        int min = 32;
        int max = 127;
        int number = random.nextInt(max - min + 1) + min;
        outputChar.write(number);
    }
} // Does a close(); even on exception or break/return inside the block.

字符集现在确定为 ASCII。

由于该文件没有说明它采用什么编码,它仍然可能以操作系统编码显示。由于没有 31% 的控制代码,记事本可能足够聪明,可以使用 ASCII 或 Windows Latin-1、Cp1252 等超集。

【讨论】:

【解决方案2】:

编译器将随机生成的数字解释为Unicode并输出汉字。我建议您对代码进行切片,不要一起生成所有整数或使用Random().format 指定格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多