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

Java中如何对二维数组每行排序?从文本文件读取数据

嘿,我来帮你把这段代码补全并实现从文本文件读取二维数组、对每行排序的功能!先梳理下你现有代码的小问题,再给出完整的优化方案:

完整实现:读取二维数组并逐行排序

你的代码目前缺少行索引递增、列索引重置的逻辑,而且没有添加排序步骤。下面是补全并优化后的完整代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Average { 
    // 定义二维数组,假设最多10行12列(可根据实际需求调整)
    static int[][] myArray = new int[10][12]; 
    static int rowIndex = 0; // 用更直观的变量名代替x

    public static void main(String[] args) {
        // 使用try-with-resources自动关闭文件流(Java 7+支持)
        try (BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"))) { 
            String line; 
            // 读取每行,同时避免数组行越界
            while ((line = in.readLine()) != null && rowIndex < myArray.length) { 
                // 按任意空白字符分割行内数值,先去除首尾空白避免空字符串
                String[] values = line.trim().split("\\s+"); 
                int columnIndex = 0; // 用columnIndex代替y,可读性更强
                
                for (String str : values) { 
                    // 跳过分割后可能出现的空字符串
                    if (str.isEmpty()) continue;
                    try {
                        int num = Integer.parseInt(str); 
                        // 避免列索引越界
                        if (columnIndex < myArray[rowIndex].length) {
                            myArray[rowIndex][columnIndex] = num; 
                            columnIndex++; 
                        }
                    } catch (NumberFormatException e) {
                        System.err.printf("行%d中存在非整数内容:%s%n", rowIndex+1, str);
                    }
                }
                
                // 对当前读取完成的行进行排序
                Arrays.sort(myArray[rowIndex]);
                // 移动到下一行
                rowIndex++; 
            }

            // 打印排序后的结果,验证功能
            System.out.println("排序后的二维数组:");
            for (int i = 0; i < rowIndex; i++) {
                System.out.println(Arrays.toString(myArray[i]));
            }
        } catch (IOException e) { 
            System.err.println("读取文件时出错:");
            e.printStackTrace(); 
        }
    }
}

关键修改&优化点

  • 变量名优化:把x/y改成rowIndex/columnIndex,代码逻辑更清晰
  • 边界安全:添加了行、列的越界判断,避免数组下标异常
  • 自动资源管理:用try-with-resources语法自动关闭文件流,无需手动调用close(),更安全
  • 异常增强:捕获NumberFormatException,友好提示文件中的非法数值
  • 排序实现:在每行读取完成后,直接调用Arrays.sort()对当前行进行升序排序(如果需要降序,可手动实现排序逻辑或反转数组)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:33:45