【问题标题】:Reading numbers from a .txt file into a 2d array and print it on console将 .txt 文件中的数字读入二维数组并在控制台上打印
【发布时间】:2015-08-29 03:11:49
【问题描述】:

所以基本上我正在尝试读取包含以下内容的 .txt 文件:

3 5 

2 3 4 5 10

4 5 2 3 7

-3 -1 0 1 5

并将它们存储到二维数组中并在控制台上打印,我从控制台得到的结果很好,但只缺少第一行 3 5,我不知道我的代码有什么问题使它忽略了第一行。 我现在得到的输出:

2  3  4  5 10 

4  5  2  3  7

-3 -1  0  1  5 

import java.io.*;
import java.util.*;

public class Driver0 {
    public static int[][] array;
    public static int dimension1, dimension2;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Project 0.");
        System.out.println("What is the name of the data file? ");
        String file = input.nextLine();
        readFile(file);
    }

    public static void readFile(String file) {
        try {
            Scanner sc = new Scanner(new File(file));
            dimension1 = sc.nextInt();
            dimension2 = sc.nextInt();
            array = new int[dimension1][dimension2];
            while (sc.hasNext()) {
                for (int row = 0; row < dimension1; row++) {
                    for (int column = 0; column < dimension2; column++) {
                        array[row][column] = sc.nextInt();
                        System.out.printf("%2d ", array[row][column]);
                    }
                    System.out.println();
                }

            }
            sc.close();
        }

        catch (Exception e) {
            System.out
            .println("Error: file not found or insufficient     requirements.");
        }
    }
}

【问题讨论】:

  • 你会错过前两个数字,因为你在这两行中得到它们:dimension1 = sc.nextInt() 和 dimension2 = sc.nextInt(),你将它们用作数组的维度。

标签: java arrays multidimensional-array


【解决方案1】:

您正在这部分代码中读取这些数字:

dimension1 = sc.nextInt();
dimension2 = sc.nextInt();

所以dimension1 获得了 3 的值,dimension2 获得了 5 的值,但您没有将它们保存到数组中。

【讨论】:

    【解决方案2】:

    试试这个代码....

    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    
    public class Proj4 {
        public static int rows, cols;
        public static int[][] cells;
        /**
         * main reads the file and starts
         * the graphical display
         */
        public static void main(String[] args) throws IOException {
            Scanner s = new Scanner(System.in);
            String file = JOptionPane.showInputDialog(null, "Enter the input file name: ");
            Scanner inFile = new Scanner(new File(file));
    
            rows = Integer.parseInt(inFile.nextLine());
            cols = Integer.parseInt(inFile.nextLine());
            cells = new int[rows][cols];
    
                    //this is were I need help
            for(int i=0; i < rows; i++) 
            {
                String line = inFile.nextLine();
                line = line.substring(0);
    
            }
    
            inFile.close();
    
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    System.out.print(cells[i][j]);
                }
                System.out.print();
        }
    

    【讨论】:

      【解决方案3】:

      您可以使用 Stream API 轻松做到这一点

      public static Integer[][] readFile(String path) throws IOException {
          return Files.lines(Paths.get(path)) // 1
                  .filter(line -> !line.trim().isEmpty()) // 2
                  .map(line -> Arrays.stream(line.split("[\\s]+")) // 3
                          .map(Integer::parseInt) // 4
                          .toArray(Integer[]::new)) // 5
                  .toArray(Integer[][]::new); // 6
      }
      
      1. 以流的形式读取文件
      2. 忽略空行
      3. 用空格分隔每一行
      4. 解析拆分的字符串值以获取整数值
      5. 创建一个整数值数组
      6. 在二维数组中收集它

      【讨论】:

        【解决方案4】:

        前两个值被保存到维度 1 和维度 2 变量中,因此当稍后调用 sc.nextInt 时,它已经读取了前两个数字并移至下一行。所以那些第一个整数不会进入数组。

        【讨论】:

          【解决方案5】:

          需要考虑的几点:

          1. 您想要使用整个文件,所以我会使用Files.readAllLines() 一次性读取整个文件。此函数返回一个List&lt;String&gt;,它将包含您文件的所有行。如果有任何空行,请将其删除,现在您就有了要为二维数组声明的行数。
          2. 每一行都是用空格分隔的,所以List&lt;String&gt; 中每一行的简单String.split() 将为您提供每行应有的列数。
          3. 分割每一行并将它们转换为整数可以使用嵌套的 for 循环来完成,这对于处理二维数组是正常的。

          例如:

          public static void main(String[] args) throws Exception {
              // Read the entire file in
              List<String> myFileLines = Files.readAllLines(Paths.get("MyFile.txt"));
          
              // Remove any blank lines
              for (int i = myFileLines.size() - 1; i >= 0; i--) {
                  if (myFileLines.get(i).isEmpty()) {
                      myFileLines.remove(i);
                  }
              }
          
              // Declare you 2d array with the amount of lines that were read from the file
              int[][] intArray = new int[myFileLines.size()][];
          
              // Iterate through each row to determine the number of columns
              for (int i = 0; i < myFileLines.size(); i++) {
                  // Split the line by spaces
                  String[] splitLine = myFileLines.get(i).split("\\s");
          
                  // Declare the number of columns in the row from the split
                  intArray[i] = new int[splitLine.length]; 
                  for (int j = 0; j < splitLine.length; j++) {
                      // Convert each String element to an integer
                      intArray[i][j] = Integer.parseInt(splitLine[j]);
                  }
              }
          
              // Print the integer array
              for (int[] row : intArray) {
                  for (int col : row) {
                      System.out.printf("%5d ", col);
                  }
                  System.out.println();
              }
          }
          

          结果:

              3     5 
              2     3     4     5    10 
              4     5     2     3     7 
             -3    -1     0     1     5
          

          【讨论】:

            猜你喜欢
            • 2014-04-06
            • 1970-01-01
            • 1970-01-01
            • 2012-09-17
            • 1970-01-01
            • 1970-01-01
            • 2014-10-29
            相关资源
            最近更新 更多