有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

以下是我目前的代码:

int[] ND1Row1 = new int[6];
for (int column = 0; column < 6; column++) {
    if (fileScan.hasNextInt()) {
        ND1Row1[column] = fileScan.nextInt();
    }
}

我只希望文件中的每一行都有一个数组


共 (4) 个答案

  1. # 1 楼答案

    int[][] ND1Row1 = new int[10][6];
    for(int column = 0; column < 6; column++){
       for(int i= 0; i < 10; column++){
          if(fileScan.hasNextInt()){
                ND1Row1[i][column] = fileScan.nextInt();
          }
       }
    }
    
  2. # 2 楼答案

    如果是文件,可以使用readline读取每一行,使用StringTokenizer从读取的行中获取整数值

  3. # 3 楼答案

    用代码将第一行传递到一个数组中 根据数量,可以在(if(fileScan.hasNextLine())之前使用a 要创建的数组。 每次你都要创建一个新的数组。我想你能找到方法

        Scanner fileScan;
        try {
             fileScan = new Scanner(new File("file destination"));
    
    
            for(......)
             if(fileScan.hasNextLine()){
                 int[] ND1Row1 = new int[6]; //create the first array
    
                for(int column=0; column<6; column++)
                    ND1Row1[column] = Integer.parseInt(fileScan.next());
    
             }//end of  if(fileScan.hasNextLine())
    
        } catch (FileNotFoundException e){e.printStackTrace();}
    
  4. # 4 楼答案

    必须单独声明每个数组,并使用嵌套for循环填充它们,因此必须知道文件中的行数。 或者,您可以计算行数,然后创建一个二维数组