将行和列设置为数组

时间:2017-09-22 22:39:09

标签: java arrays loops while-loop io

我的代码错误地计算列数时出现问题。我必须从文本文件中读取有关我应该具有的作为矩阵的维度的信息,但我似乎遇到了该列的问题。第一个数字应该是矩阵中的行数。

输入文件上有什么:

3
8 5 -6 7
-19 5 17 32
3 9 2 54

以下是确定信息的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) throws FileNotFoundException {

        File f = new File("testwork.txt");
        Scanner in = new Scanner(f);
        int numRows = in.nextInt();

        ArrayList<Integer> columnCheck = new ArrayList<Integer>();

        while (in.hasNextLine()) {  
        columnCheck.add(in.nextInt());
        break;
        }

        int numColumns = columnCheck.size();

        System.out.println(numRows, numColumns);
        in.close();
    }

}

我从这段代码得到的输出是3(行数)12(列数)。显然这是错误的,我知道问题是while循环不断重复检查循环中有多少个数字,但我无法弄清楚如何修复它。我应该用while循环更改什么才能使程序只占用4列?

3 个答案:

答案 0 :(得分:1)

这就是你实际想要实现的目标

public static void main(String[] args) throws FileNotFoundException {
    File f = new File("testwork.txt");
    Scanner in = new Scanner(f);
    int numRows = in.nextInt();

    ArrayList<Integer> columnCheck = new ArrayList<Integer>();
    int numColumns = 0;

    while (in.hasNextLine()) {  
        Scanner s2 = new Scanner(in.nextLine());
        numColumns++;

        while (s2.hasNextInt()) {
            columnCheck.add(s2.nextInt());
        }
    }

    System.out.println(numRows, numColumns);
    in.close();
}

答案 1 :(得分:0)

尝试使用

while (in.hasNext()) {...}

我认为问题可能是hasNextLine()读取了输入键“\ n”,这就是它读取所有数字而不是一行的原因。使用in.hasNextLine()完成该行之后,您将需要进行另一次检查,以确保您到达文本文件中的下一行。

答案 2 :(得分:0)

这个while循环是错误的:

while (in.hasNextLine()) {  
    columnCheck.add(in.nextInt());
    break;
}

首先获取该行,然后将每个整数存储在ArrayList中。

这样做:

while (in.hasNextLine()) {  
    String column = in.nextLine();
    String columnArr[] = column.split("\\s+"); // split it by space
    System.out.println("Column Numbers:" +  columnArr.length());
    break;
}