2 回答

TA貢獻1802條經驗 獲得超4個贊
在這里做了一些改變。我讀到“NODE_COORD_SECION”然后開始解析存儲行的ans。我不是在“”上拆分,而是在“”上拆分并存儲值。
public class Tree {
ArrayList<String[]> storing;
public Tree() throws Exception {
File file = new File("C:/Users/joaki/Desktop/burma14.tsp");
Scanner sc = new Scanner(file);
storing = new ArrayList<String[]>();
String nextValue = null;
while (sc.hasNextLine()) {
String line = sc.nextLine();
if("NODE_COORD_SECTION".equals(line)){
while (sc.hasNextLine()) {
nextValue = sc.nextLine();
storing.add(nextValue.trim().split(" "));
}
}
}
sc.close();
}
public static ArrayList<String[]> returnScanner() throws Exception {
Tree tree = new Tree();
return tree.storing;
}
public static void main(String[] args) throws Exception {
ArrayList<String[]> storedValues = returnScanner();
String[] firstLine = storedValues.get(0);
String[] secondLine = storedValues.get(1);
for (int i = 0; i < firstLine.length; i++) {
System.out.println(firstLine[i]);
}
}
}
我的輸出:
1
565.0
575.0

TA貢獻1775條經驗 獲得超11個贊
使用掃描儀移動到下一行,直到遇到短語“NODE_COORD_SECTION”。然后接下來的幾行是你的數據線。它們都符合格式,因此您可以使用 split 來獲取第二個和第三個元素。
當您到達標有“EOF”的行時,停止讀取和存儲在您的數組中。
你有多關心 TSP 文件的標題?如果要存儲此信息并根據文件中的數據檢查它是否正確,而不是僅運行到“NODE_COORD_SECTION”行,則需要查找行:“DIMENSION”并將值存儲為 int。然后根據您的 ArrayList“存儲”中的最終總數檢查此值
添加回答
舉報