2014-05-01 141 views
-2

我试图使用java中的数据结构来模拟节点网络。让我们假设我有4个节点的网络,即0 1 2 3。现在,我创建数据的文本文件,如下所示:从文件中读取数据并形成数据结构Info

0 1 
1 2 
2 3 
0 3 

的数据表示节点之间的连接。有一个从0到1等的链接。所有的链接都是单向的。现在我想寻求你们的帮助,知道如何阅读这个文本文件并形成数据结构。哪个数据结构对此可行?我将在整个模拟过程中使用这个数据结构来在对象之间发送数据。哪一个会更好,使用树木或hashmaps?当读取文本文件并形成数据结构时代码将如何?这个你能帮我吗。

+0

我们无法为您编写程序。你有现有的代码,我们可以看看你有问题吗? – BradleyDotNET

回答

0

我会用linked list。当它们之间“传输”数据时,确保你标记了哪一个启动了数据包,这样你的例子中的循环排列不会超出堆栈。

1

你可能想要做的是创建一个节点类,其中有一个字段指示该节点能够连接到哪个节点。然后您需要从文件中读取连接,并使用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]); 
    } 

祝你好运!

+0

感谢您的时间levenal。现在,如果想在其他类中使用此列表来检查我是否有从x到y的路径。可能吗?并且如果有一个节点有两个传出节点...就像1有0和2作为传出邻居,我的文本文件就像10,然后是1 2 ....如果有多个节点之间的这种多重连接..我仍然可以使用数组列表吗?或者我应该使用图形? – user3029915

+0

@ user3029915您可以遍历ArrayList检查每个数组以获取所需的值,例如[1,2]的数组显示1到2之间的连接。通过多个节点,您可能会向ArrayList添加更多数组,以表示连接,它不应该是一个问题,但你可能想指定一个更大的默认大小。 – Levenal

相关问题