Java - 如何将文件的下一列放入数组中



这是我正在读取的文件:

>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 循环准备的代码似乎没有正确执行。任何帮助将不胜感激。

你可以去掉第二个 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

尝试这样的事情:

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();

最新更新