我希望能够读取文本文件的行和列并将数据放入矩阵中。这就是我到目前为止所得到的。我有一个矩阵类,其中有一个名为 int 类型元素的数据成员,它是一个二维数组 [][]。
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
scanner.next(); // removes the first line in the input file
int rows = scanner.nextInt();
int cols = scanner.nextInt();
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
System.out.println(rows);
System.out.println("/n");
System.out.println(cols);
}
}
示例文本文件如下。我想获取行和列,以便我可以动态声明矩阵,然后存储其值。我收到错误消息说 INPUTMISMATCH 异常。帮助将不胜感激。
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix>
最佳答案
来自javacdocs ,“如果下一个标记与 Integer 正则表达式不匹配,或者超出范围”,则会引发 InputMismatchException
。
您正在尝试将字符串“row = 2”扫描为整数。在这种情况下,您不能使用 nextInt
。尝试 nextLine
,然后在 =
上拆分以获取值。
示例:
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
关于java - 扫描仪类别和跳过模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5001526/