我从一个看起来像这样的文件中读取
5
0 3 1 4 2
4 0 6 1 4
1 2 0 6 5
6 3 1 0 8
4 1 9 3 0
第一个数字无关紧要。我想从第 2 行开始读取。我能够读取第 1 行并存储它,但我无法读取数组的其余部分。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TSM {
private static int numOfCities;
private static int[][] arr;
public static void main(String[] args) throws NumberFormatException, IOException{
numOfCities = 0;
BufferedReader br = new BufferedReader(new FileReader("/Users/sly/Desktop/tsp.txt"));
String line = " ";
String [] temp;
while ((line = br.readLine())!= null){
if(line.trim().length() ==1) { //set value of first line in file to be numOfCities
numOfCities = Integer.parseInt(line);
System.out.println("There are"+ " " + numOfCities+ " " + "Number of cities");
} else{
temp = line.split(" "); //split spaces
for(int i = 0; i<arr.length; i++) {
for (int j = 0; j<arr.length; j++) {
arr[i][j] = Integer.parseInt(temp[i]);
}
}
}
}
printArray();
}
public static void printArray () {
for (int i =0; i <arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]);
}
System.out.println("");
}
}
}