Search code examples
javaparent-childa-star

an object where it has a parent and an action and each parent has a parent and an action


How can I do this in Java

public class State implements Comparable<State> {
    //other attbs;
    State parent;
    String actionFromParent;
// other code
}

where x is an object of type State and each parent itself has an action from parent. I want to do this until I have actionFromParent == null.

I don't know how many parents there are. I'm using this to print the path for A* algorithm. I'm stuck at printing the path after x (state currentnode) satisfies the goal, I print all actionfromparents of its child nodes.

System.out.println(x.actionFromParent);
System.out.println(x.parent.actionFromParent);
System.out.println(x.parent.parent.actionFromParent);
System.out.println(x.parent.parent.parent.actionFromParent);
.....
until  (x.parent.parent.parent.....parent.actionFromParent == null)

Solution

  • That is what you want:

    while(x.parent.actionFromParent != null){
        System.out.println(x.actionFromParent);
        System.out.println(x.parent.actionFromParent);
        x = x.parent;
    }