简体   繁体   中英

Java: How can I load from a save file in the following situation?

I am making a graph editor as an assignment. Before I proceed I have to mention that each node has x and y coordinates, a width and a height and a name, and each edge connects 2 nodes. We had to create custom save files as following: - first line having the number of nodes (N) and edges (E) -the next N lines, each describes a node (x, y, width, height, name) -the next E lines, each describes an edge ( each edge is described by the indices of the nodes that it connects) An example of such a file would be:

3 2
2 0 1 1 Name1
1 1 1 1 Name2
3 2 1 1 Name3
0 1
1 2

Now I have to make a load method that generates a graph based on a save file. I reckon I have to scan the file line by line and create the graph. However the implementation of that gives me some trouble. Let's take into consideration the first line 3 2 . I should scan the 3 and the 2 and then create 3 nodes and 2 edges. However, I am not sure how can I do that correctly because whenever I am creating a node I am using his x, y, width, height, name (which are on the next lines of the savefile) like that:

Node A = new Node(2, 0, 1, 1, "Name1");
Node B = new Node(1, 1, 1, 1, "Name2");
Node C = new Node(3, 2, 1, 1, "Name3");

For example.

I am also not sure how can I name the node object, because each node that i have to create has to have a different variable name (like ABC) above, because I am putting them in an ArrayList. By that I mean I can not just read the 3 from the save file and then create the graph by doing something like:

for (i=0; i < nrReadFromSaveFileWhichIs3InThatCase ; i++){
     Node A = new Node (??????)
     //add the node to the arraylist
     ...

}

If you need additional info let me know and I will put more of my code here as an edit. Hope that was clear enough, and thank you for your time!

as I understand you have an issue with creating node objects inside the loop, I suggest you create an array of nodes and each time you read a line of node you store it inside the array:

 // get Nbr_of_nodes by reading the file
 Node myNodes[] = new Node[Nbr_of_nodes] ;
 for (i=0; i < Nbr_of_nodes ; i++){
 //create and add the node to the ArrayList
  myNodes[] = new Node(x, y, w, h, "Name");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM