0

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?

2
  • 1
    we have no idea how you defined the functions you are using in this for loop.. Commented May 16, 2015 at 2:10
  • can you post the methods getStartNode(), getEndNode(), getCost()? and also where are you assigning the startnode, nodes and cost variables Commented May 16, 2015 at 2:11

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.