你可能想要做的是創建一個節點類,其中有一個字段指示該節點能夠連接到哪個節點。然後您需要從文件中讀取連接,並使用Node構造函數中的數據建立連接。
關於讀取數據,您可以使用ArrayList,Array和Buffered Reader來完成此操作。它首先設置ArrayList,然後使用BufferedReader獲取連接,將每個對存儲在數組中並將其存儲在ArrayList中以供引用。
//ArrayList which will hold the arrays containing the connections
ArrayList<int[]> connections = new ArrayList<int[]>(4);
Path pathway = Paths.get("D:/Users/mgreenma/Desktop/tester.txt");//Path to file
//Using a BufferedReader and FileReader we access the file
try(BufferedReader reader = new BufferedReader(new FileReader(pathway.toFile()))){
String line = "";
Scanner sc = new Scanner(line);
while((line = reader.readLine()) != null){ //Read each line until there are no more
sc = new Scanner(line); //Set up a scanner
int[] conn = new int[2]; //An array to hold each pair of nodes
conn[0] = sc.nextInt(); //Get first node
conn[1] = sc.nextInt(); //And the second
connections.add(conn); //Add to the ArrayList
}
sc.close(); //Close scanner
} catch (IOException io){
System.out.println("Error: " + io.getMessage());
}
for(int[] i : connections){//Print our connections list
System.out.println("Connection: " + i[0] + "," + i[1]);
}
祝你好運!
我們無法爲您編寫程序。你有現有的代碼,我們可以看看你有問題嗎? – BradleyDotNET