[英]Reading in a 2D array from a file through the command line in Java
我需要从文件中读取矩阵。 我可以正常读取文件,但是如果每行以空格开头,则会出现错误。 我该如何解决? 我不知道我是否做对了。 这是我的代码的一部分:
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class factor {
public static void PrintMatrix(double[][] matrix) {
int size = matrix[0].length;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("%4.4f ", matrix[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("You must supply a file to load the matrix from.");
return;
}
Scanner s;
double[][] a;
double[][] l;
double[][] u;
String line;
int n;
String[] nums;
try {
s = new Scanner(new File(args[0]));
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
return;
}
if (s.hasNext()) {
line = s.nextLine();
nums = line.split("\\s+");
n = nums.length;
a = new double[n][n];
l = new double[n][n];
u = new double[n][n];
for (int i = 0; i < n; i++) {
a[0][i] = Double.parseDouble(nums[i]);
}
} else {
System.out.println("Nothing found in file.");
return;
}
for (int i = 1; i < n; i++) {
nums = s.nextLine().split("\\s+");
for (int j = 0; j < n; j++) {
a[i][j] = Double.parseDouble(nums[j]);
}
}
s.close();
您可以尝试在line = s.nextLine()
之后使用line.trim()
删除空格,以解决此问题。 Trim删除了前导和尾随空格,因此它不应该干扰.split()
的分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.