[英]Reading a 2d array from an external file
我知道以前有人問過這個問題,但是在閱讀了其他人的帖子后我仍然感到困惑。 我正在嘗試從外部文件中讀取成本鄰接矩陣並使用它來填充我將最終打印的二維數組。 我能夠讀取文本文件中的信息,但我的矩陣沒有正確填寫。 現在它看起來像這樣:
我要拍攝的東西看起來像這樣,
New York Boston Atlanta St.Paul
New York 0 120 400 -1
Boston 120 0 1700 500
Atlanta 400 1700 0 -1
St.Paul -1 500 -1 0
到目前為止,這是我的代碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Lab12MU2 {
public static void main(String[] args) {
String fileName;
FileReader myFileRead;
String[][] matrix;
boolean populated = false;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
fileName = scn.nextLine();
try {
myFileRead = new FileReader(fileName);
BufferedReader buffRead;
buffRead = new BufferedReader(myFileRead);
Scanner input = new Scanner(new File(fileName));
int dim = 5;
matrix = new String[dim][dim];
int i, j;
for (i = 0; i < dim; ++i) {
for (j = 0; j < dim - 1; ++j) {
if (input.hasNext()) {
matrix[i][j] = input.nextLine();
}
}
}
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
populated = true;
myFileRead.close();
}
catch (Exception ex) {
System.out.println("ERROR: File not found");
}
}
}
感謝您在修復我的矩陣以使其看起來接近我想要的結果的任何幫助。 另外,這是文本文件: https://www.dropbox.com/s/owikpr2vqx31kjn/CAM.txt?dl=0
New York, Boston, Atlanta, St. Paul
0, 120, 400, -1
120, 0, 1700, 500
400, 1700, 0, -1
-1, 500, -1, 0
代碼后的注釋。
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Lab12MU2 {
public static void main(String[] args) {
Path path = Paths.get("CAM.txt");
try (Stream<String> lines = Files.lines(path)) {
List<String[]> list = lines.map(line -> line.split(", "))
.collect(Collectors.toList());
String[][] matrix = list.toArray(new String[][]{});
boolean first = true;
for (int col = 0; col < matrix[0].length; col++) {
if (first) {
first = false;
}
else {
System.out.print(" ");
}
System.out.print(matrix[0][col]);
}
System.out.println();
for (int row = 1; row < matrix.length; row++) {
first = true;
for (int col = 0; col < matrix[row].length; col++) {
if (first) {
first = false;
}
else {
System.out.print(" ");
}
System.out.printf("%" + matrix[0][col].length() + "s", matrix[row][col]);
}
System.out.println();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
上面的代碼假定文件名是CAM.txt ,而不是從用戶那里獲取文件名。 請注意,根據上面的代碼,文件必須在工作目錄中。
該代碼使用stream API和try-with-resources 。
請參閱方法printf
的文檔。
當我使用您問題中的文件運行上述代碼時,我得到以下 output:
New York Boston Atlanta St. Paul
0 120 400 -1
120 0 1700 500
400 1700 0 -1
-1 500 -1 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.