从.txt文件中读取数字到二维数组中并在控制台上打印出来

5
基本上我正在尝试读取一个包含以下内容的 .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(),你将使用它们作为数组的维度。 - La VloZ
5个回答

1

您正在阅读代码的这部分数字:

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

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

1
尝试这段代码....
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();
    }

1
你可以使用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. 在2D-Array中收集它

0

需要考虑以下几点:

  1. 您想要使用整个文件,因此我建议使用 Files.readAllLines() 一次性读取整个文件。该函数返回一个 List<String>,其中包含文件的所有行。如果有任何空行,请将它们删除,现在您就可以声明二维数组的行数了。
  2. 每行都是以空格分隔的,因此对于您的 List<String> 中的每一行进行简单的 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

0

前两个值被保存在dimension1和dimension2变量中,因此当稍后调用sc.nextInt时,它已经读取了前两个数字并移动到下一行。因此,这些第一个整数不会进入数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接