简体   繁体   中英

Java - Initialize Variable on Condition

I'm writing a Java program to simulate the A* algorithm, and need to pass to my a() function two parameters, initial state and goal state . However, to ensure I have the correct goal state, I check to see if it's heuristic value is 0. If it is, then I mark boolean goal == true else I mark it false.

I was wondering, is there any way I could initialize a variable State goal to that goal state, by checking it's boolean value?

for(int i = 0; i < states.size(); i++)
    states.get(i).isGoal();

states is a HashMap of states for the algorithm, and isGoal() is a method that sets each state's boolean flag, depending upon its heuristic value.

Have your isGoal() return a boolean and set the State goal after checking the isGoal flag. ie

for(int i = 0; i < states.size(); i++)
    if(map.get(i).isGoal()){
        map.get(i).setGoal();
    }

I think you want something like this:

for(int i = 0; i < states.size(); i++) {
        if(map.get(i).isGoal()){
            //instantiate wherever you want if goal is true
            map.get(i).setGoal();
        } else {
            //instantiate wherever you want if goal is false
        }
    }

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