将txt文件保存到二维矩阵
save txt file to 2D matrix
我是 java 编程的初学者,我不知道如何将 txt 信息保存到二维矩阵。接下来我要做的操作是转置矩阵等
我的代码:
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]]
是的,它是正确的,但图形输出不同。还有其他选择吗?
尝试这样的事情
System.out.println("[");
for (int i = 0; i < myArray.length; i++) {
System.out.print(" [ ");
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println("]");
}
System.out.println("]");
我是 java 编程的初学者,我不知道如何将 txt 信息保存到二维矩阵。接下来我要做的操作是转置矩阵等
我的代码:
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]]
是的,它是正确的,但图形输出不同。还有其他选择吗?
尝试这样的事情
System.out.println("[");
for (int i = 0; i < myArray.length; i++) {
System.out.print(" [ ");
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println("]");
}
System.out.println("]");