简体   繁体   English

我如何将 Java 控制台 Output 读入 2d n*m 双矩阵/数组

[英]How could I read Java Console Output into a 2d n*m double matrix/array

here is code:这是代码:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadContents {
    public static void main(String[] args) throws IOException {
        File file = new File("file1.txt");
        List<float[]> list = new ArrayList<float[]>();
        Scanner scanner = new Scanner(file).useDelimiter("\n");



        while (scanner.hasNext()) {     
            String[] values = scanner.next().trim().split(" "); 
             float[] floats = new float[values.length];
             for (int i = 0; i < values.length; i++) {
                 floats[i] = Float.parseFloat(values[i]);
                 }
                 list.add(floats);
                 } 
                 float[][] values = new float[list.size()][];
                 for (int i = 0; i < list.size(); i++) {
                     values[i] = list.get(i);
                     for (int j = 0; j < values[i].length; j++) {
                         System.out.print(values[i][j] + " ");

                         }
                         System.out.println();
                 }


                int row =values.length;
                 int col=values[0].length;

                 System.out.println(row);
                 System.out.println(col);

    //******************************************************************************************************************
                  System.out.println();
                   double sum;
                   double avg=0;

               for (int p = 0; p < col; p++){
                   sum=0;
                   for (int k = 0; k < row; k++){ 
                     sum = sum + values[k][p]; 
                     //avg=((double)sum / row);

                   }
                    avg=((double)sum / row);
                   System.out.print("average"+p+"=");
                  System.out.printf("%5.2f\n", avg);
               }

it gives output as file content in 2d matrix and also print averages of each column of "values[][]" matrix on console screen.now i want to print the matrix containing all averages calculated previously into single 2d n*m array.它提供 output 作为 2d 矩阵中的文件内容,并在控制台屏幕上打印“values [] []”矩阵的每一列的平均值。现在我想打印包含先前计算的所有平均值的矩阵到单个 2d n * m 数组中。 pls guide me.请指导我。

In the first place you shouldn't be dumping the result to the console.首先,您不应该将结果转储到控制台。

Instead, store the result into a variable.相反,将结果存储到变量中。

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

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