【发布时间】:2021-10-07 20:25:40
【问题描述】:
我是 java 编程的初学者,我不知道如何将 txt 信息保存到 2D 矩阵。我要做的下一个操作是转置矩阵等。
我的代码:
File text = new File("/matrix.txt");
System.out.print("\Path to file: ");
Scanner sc = new Scanner(System.in);
String m = sc.nextLine();
BufferedReader br = new BufferedReader(new FileReader("m));
String st;
System.out.println("matrix");
while ((st = br.readLine()) != null)
System.out.println(st);
输出例如:
matrix
1 0 0 0 0 1 1
0 1 0 0 1 0 0
0 0 1 0 1 1 1
0 0 0 1 0 0 1
我需要相同的输出,在矩阵中萌芽。谢谢
我试过了:
Scanner sc = new Scanner(new BufferedReader(new FileReader("/matrix.txt")));
int rows = 4;
int columns = 7;
int [][] myArray = new int[rows][columns];
while(sc.hasNextLine()) {
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<line.length; j++) {
myArray[i][j] = Integer.parseInt(line[j]);
}
}
}
System.out.println(Arrays.deepToString(myArray));
但输出不是我所期望的
[[1, 0, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 0, 1]]
是的,这是正确的,但图形输出不同。是否存在其他选择?
【问题讨论】:
-
能否包含 matrix.txt 的内容,以及一些显示您目前尝试过的代码?
标签: java file matrix java.util.scanner filereader