我怎么能将Java控制台输出读入2d n * m双矩阵/数组

时间:2022-09-28 14:44:25

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. pls guide me.

它在2d矩阵中给出输出作为文件内容,并且还在控制台屏幕上打印“values [] []”矩阵的每列的平均值。现在我想打印包含先前计算的所有平均值的矩阵到单个2d n * m数组中。请指导我。

1 个解决方案

#1


0  

In the first place you shouldn't be dumping the result to the console.

首先,您不应该将结果转储到控制台。

Instead, store the result into a variable.

而是将结果存储到变量中。

#1


0  

In the first place you shouldn't be dumping the result to the console.

首先,您不应该将结果转储到控制台。

Instead, store the result into a variable.

而是将结果存储到变量中。