【问题标题】:Setting row's and column's to an array将行和列设置为数组
【发布时间】:2017-09-22 22:39:08
【问题描述】:

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

输入文件上有什么:

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 列?

【问题讨论】:

  • 无法确认:numColumns 为 1,因为你打破了

标签: java arrays loops while-loop io


【解决方案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();
}

【讨论】:

    【解决方案2】:

    尝试使用

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

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

    【讨论】:

      【解决方案3】:

      这个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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 2017-06-11
        • 2016-09-12
        相关资源
        最近更新 更多