2017-09-22 84 views
0

我的代码有问题,不正确地计算列数。我必须从文本文件中读取关于我应该具有的作为矩阵的维度的信息,但我似乎遇到了该列的问题。第一个数字应该是矩阵中的行数。将行和列设置为数组

什么是对输入的文件:

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

+0

不能确认:为numColumns是1,因为你打破 – Anona112

回答

0

尝试使用

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

我认为这个问题可能是hasNextLine()读了回车键“\ n”,这就是为什么它是阅读,而不是一个线上的所有数字。在使用in.hasNextLine()完成该行后,您需要进行另一次检查,以确保您能够到达文本文件中的下一行。

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(); 
} 
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; 
}