java - 将 .txt 文件中的数字读入二维数组并在控制台上打印

标签 java arrays multidimensional-array

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

3 5 

2 3 4 5 10

4 5 2 3 7

-3 -1 0 1 5

并将它们存储到 2D 数组中并在控制台上打印,我从控制台得到的结果很好但只缺少第一行 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();

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

关于java - 将 .txt 文件中的数字读入二维数组并在控制台上打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30814412/

相关文章:

java - Java 中的 C++ Pair<L,R> 等价物是什么?

c - 在C中获取 "char *namelist[]"中项目的总数

php - 使用数组的数字键从数据库中存储多维数组

objective-c - ARC Objective-C 中的 C 风格多维数组

多维动态数组中的 C++ 对象构造

java - 如何测试我的 Web 应用程序可以处理 "100 users"?

java - Wicket 添加一个大的 Pdf 作为资源

javascript::如何使用数组中的javascript变量在传单上绘制多边形

java - 确定 EMR 作业在 Map 与 Reduce 任务上花费了多少时间的最佳方法是什么?

javascript - 如何读取/访问名称 :values of Objects stored within an Array?