繁体   English   中英

java txt 文件的行和列并变成二维数组

[英]java txt file of rows and columns and turn into a 2-D array

如何在没有 ArrayList 的情况下将行和列中整数的 txt 文件转换为二维数组并打印出来。 txt 文件也是两个文件,当我使用给定的锯齿状 txt 文件时,代码应该适用于锯齿状数组。 我使用了 split 方法,但它只适用于 columnn,所以我很困惑这次如何能够拆分每一行和每一列并将其放入二维数组中。 我还应该找到每一行和每一列的平均值,这就是拆分很重要的原因。

更新:到目前为止,我已经这样做了,但是我在 row 和 col 上收到一个错误,说可能从 double 到 int 的有损转换,我不明白,而且我现在如何找到每行和 col 的平均值

File file = new File("ind.txt");
        Scanner scan = new Scanner(file);

        double rows = scan.nextDouble();
        double col = scan.nextDouble();
        double [][] arr = new double[rows][col];   
        for(int i = 0; i < rows; i++) {        
            for(int j = 0; j < col; j++) {
                arr[i][j] = scan.nextDouble();
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();

您的代码必须更改为:

    File file = new File("ind.txt");
    Scanner scan = new Scanner(file);

    //double rows = scan.nextDouble();
    //double col = scan.nextDouble();
    int rows = (int)scan.nextDouble();  //or int rows = (int)scan.nextInteger(); 
    int col = (int)scan.nextDouble();
    double [][] arr = new double[rows][col];   

    for(int i = 0; i < rows; i++) {  
        double currentRowAVG=0;      
        for(int j = 0; j < col; j++) {
            arr[i][j] = scan.nextDouble();
            currentRowAVG+=arr[i][j]/col;
            System.out.print(arr[i][j] + " ");
        }
        System.out.println();
    }

    double column0AVG=0;  
    for(int i = 0; i < rows; j++) {            
        column0AVG+=arr[i][0]/rows;            
    }
    double column1AVG=0;  
    for(int i = 0; i < rows; j++) {            
        column0AVG+=arr[i][1]/rows;            
    }

您也可以将文件手动读取为文本,然后分离数据并将分离的数据转换为您想要的任何类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM