【问题标题】:Java - How to put the next column of a file into an arrayJava - 如何将文件的下一列放入数组中
【发布时间】:2015-01-17 18:19:09
【问题描述】:

这是我正在读取的文件:

>18  64  94  54  34  44
>40  26  26  92  96  34
>56  24  40  92  70  58
>92  72  12  46  46  56
>50  28  2  64  12  58
>98  28  40  88  86  20
>46  56  100  60  52  12
>82  70  98  18  50  30
>58  36  98  4  74  76
>76  28  72  74  74  60

这是我的代码:

>package exercise;
>
>import java.io.File;
>import java.io.FileNotFoundException;
>import java.util.Scanner;
>
>public class Lab1 {
>
>   public static void main(String[] args) throws FileNotFoundException {
>       
>       File file = new File("numberData.csv");
>       Scanner fileScan = new Scanner(file);
>       
>       int[] ND1Column1 = new int[10];
>       int[] ND1Column2 = new int[10];
>       int[] ND1Column3 = new int[10];
>       int[] ND1Column4 = new int[10];
>       int[] ND1Column5 = new int[10];
>       int[] ND1Column6 = new int[10];
>       int[] ND2Column1 = new int[16];
>       int[] ND2Column2 = new int[16];
>       int[] ND2Column3 = new int[16];
>       int[] ND2Column4 = new int[16];
>       
>       
>       for(int row = 0; row < 10; row++)
>       {
>           ND1Column1[row] = fileScan.nextInt();
>           fileScan.nextLine();
>       }
>       for(int row = 0; row < 10; row++)
>       {   
>           fileScan.nextInt();
>           ND1Column2[row] = fileScan.nextInt();
>           fileScan.nextLine();
>       }
>       
>       File file2 = new File("numberData2.csv");
>       Scanner fileScan2 = new Scanner(file);
>       
>       System.out.print(ND1Column2[0]);
>   }

我成功地将第一列放入数组中。我只需要弄清楚如何将以下列放入自己的数组中。我在这里为我的第二个 for 循环提供的代码似乎没有正确执行。任何帮助将不胜感激。

【问题讨论】:

  • 好像没有你怎么知道?

标签: java arrays file


【解决方案1】:

您可以摆脱第二个 for() 循环并将代码合并到一个嵌套的 for() 循环中。

您还可以通过将文件读入二维数组、矩阵来节省大量代码。矩阵的写法如下:

int[][] ND1Column = new int[6][10];
int[][] ND2Column = new int[16][10];

for (int row = 0; row < 6; row++) {
    for (int col = 0; col < 10; col++) {
        if (!fileScan.hasNextInt()) fileScan.nextLine();
        ND1Column[row][col] = fileScan.nextInt();
    }
}

//Do the same thing for ND2Column except give the array 16 cols and 4 rows

【讨论】:

    【解决方案2】:

    试试这样的:

    BufferedReader br = new BufferedReader(new FileReader("numberData.csv"));
    String line;
    int i = 0;
    while ((line = br.readLine()) != null) {
       i++;
       switch(i):
       case 1:
          // put line inside ND1Column1
       case 2:
          // put line inside ND1Column2
       //etc
    }
    br.close();
    

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 2021-08-18
      • 2019-05-19
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多