【问题标题】:How to make an array for each individual row of integers in a file如何为文件中的每一行整数创建一个数组
【发布时间】:2015-01-17 23:13:33
【问题描述】:

这是文件:

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

我只想在我的文件中的每一行都有一个数组。

【问题讨论】:

    标签: java arrays file


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用代码将第一行传递到一个数组中 您可以根据数量使用 for(before) (if(fileScan.hasNextLine())) 要创建的数组。 每次你必须创建一个新数组。我想你可以找到方法。

            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】:
          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();
                }
             }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-11
            • 2021-10-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-22
            • 1970-01-01
            • 2021-12-26
            相关资源
            最近更新 更多