Reputation: 503
I got 2 files(nodes and cost) in the following format
Node file as (Startnode, endnode)
A B
A C
Cost file as(node, cost)
A 6
B 5
C 8
If the startnode specified by the user is 'A' , then the following method should search for A in node file and then add the corresponding end nodes (in this case B, C)
to the list neighbournodes
and if those end nodes match the nodes in cost file, then those corresponding costs (in this case 5, 8) should be added to list h_cost
So, I got the following loop to do this. my neighbournodes
is working fine (i.e. it is outputting B,C) but somehow my h_cost
doesn't output 5, 8 instead it is outputting the empty list.
for(int i=0; i<size; i++) {
if(startnode.equalsIgnoreCase(nodes[i].getStartNode()))
{
neighbournodes.add(nodes[i].getEndNode());
int newi = i;
if(nodes[newi].getEndNode().equalsIgnoreCase(cost[i].getNode()))
{
h_cost.add(cost[i].getCost());
}
}
}
System.out.println("neighbouring nodes are "+neighbournodes);
System.out.println("H_cost is "+h_cost);
I am not sure where my loop is faulty, can any one be able to let me know where I am going wrong? Am I supposed to use enhanced for loop?
Upvotes: 0
Views: 91
Reputation: 24197
You should not be using the same index variables for the loops. Try this:
for(int i = 0; i < size; i++) {
if(startnode.equalsIgnoreCase(nodes[i].getStartNode())) {
neighbournodes.add(nodes[i].getEndNode());
for(int j = 0; j < cost.length; j++) {
if(nodes[i].getEndNode().equalsIgnoreCase(cost[j].getNode())) {
h_cost.add(cost[j].getCost());
}
}
}
}
System.out.println("neighbouring nodes are "+neighbournodes);
System.out.println("H_cost is "+h_cost);
The logic seems ok to me but using same index may mess up its value. Also I assume cost.length
will be equal to entries in the cost file.
Upvotes: 3