簡體   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