【问题标题】:How can I get the size of the rows and columns from input text file?如何从输入文本文件中获取行和列的大小?
【发布时间】:2017-03-12 04:06:19
【问题描述】:

我想从此文件文本中获取行和列的长度。我怎样才能做到这一点?谢谢!

in.txt

2 1 1 8

1 1 4 15

0 3 2 9

public static void main(String[] args) {

    int[][] arr = new int[3][4];

    File inputFile = new File("in.txt");
    try {
        Scanner scanF = new Scanner(inputFile);

        for (int i = 0; i < 3; i++) {
            String line = scanF.nextLine();
            String valVar[] = line.split(" ");
            for (int j = 0; j < 4; j++) {
                arr[i][j] = Integer.parseInt(valVar[j]);

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

【问题讨论】:

  • 长度是什么意思?

标签: java arrays matrix


【解决方案1】:

您也可以使用缓冲阅读器。

            int maxRows = 0;
            int maxColumn = 0;
            try {
                Scanner scanF = new Scanner(inputFile);
                String line = scanF.nextLine();
                while (line != null) {
                    if (line.trim().length() > 0) {
                        maxRows++;
                        String valVar[] = line.split(" ");
                        if (maxColumn < valVar.length) {
                            maxColumn = valVar.length;
                        }
                    }
                    try {
                        line = scanF.nextLine();
                    } catch (NoSuchElementException e) {
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多