You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序写入0-100随机整数后无法打印内容,需升序返回求解决

嘿,我来帮你排查下问题!从你给出的代码片段来看,大概率是几个常见的IO操作细节没处理好——比如PrintWriter没正确初始化、写完数据后没关闭流,或者读取文件的逻辑缺失。我先把完整的可运行代码写出来,再给你拆解关键点:

完整修正代码

import java.io.*;
import java.util.Arrays;
import java.util.Random;

public class RandomIntegerFile {
    public static void main(String[] args) throws IOException {
        File f = new File("integerFile.txt");
        // 如果文件已存在,先删除重建(避免追加旧数据干扰)
        if (f.exists()) {
            f.delete();
        }
        f.createNewFile();

        // 生成100个0-100的随机整数
        int arr[] = new int[100];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(101); // nextInt(101)才会包含100哦
        }

        // 写入文件:用try-with-resources自动关闭流,避免数据丢失
        try (FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw)) {
            for (int num : arr) {
                pw.println(num); // 每个数字单独一行,后续读取更方便
            }
        }

        // 从文件读取数字
        int[] readArr = new int[100];
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            int index = 0;
            while ((line = br.readLine()) != null && index < 100) {
                readArr[index++] = Integer.parseInt(line);
            }
        }

        // 升序排序并打印结果
        Arrays.sort(readArr);
        System.out.println("升序后的文件内容:");
        for (int num : readArr) {
            System.out.println(num);
        }
    }
}

你可能踩的几个坑

  • PrintWriter初始化不完整:你代码里PrintWriter pw = ...没写完,正确写法是new PrintWriter(fw)。而且一定要确保流被关闭——我用了try-with-resources语法,它会自动帮我们关闭流,避免因为忘记close()导致缓冲区数据没刷到磁盘(这是很多人碰到“写了但看不到内容”的核心原因)。
  • 追加写入的干扰:你原本用了FileWriter(f, true)的追加模式,如果之前文件有内容,新数字会加在后面,读取时会超出100个的预期,甚至导致数组越界。如果每次运行都要生成全新的100个数字,删除旧文件重建更稳妥。
  • 读取逻辑缺失:你只提到了写入,但没写读取文件的代码——要打印升序内容,得先把文件里的数字读出来放到数组里,才能排序输出。
  • 随机数范围的小细节:random.nextInt(101)才会生成0到100的整数(nextInt的参数是不包含的上限),如果写nextInt(100)只能到99,这点别搞混啦。

内容的提问来源于stack exchange,提问作者joe caled

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:56:49