开发者

Refresh Java argument

开发者 https://www.devze.com 2023-01-05 20:36 出处:网络
I am writing a program for a programming game called robocode. The problem is here: void wallScan(boolean While){

I am writing a program for a programming game called robocode. The problem is here:

    void wallScan(boolean While){
    stop();
    getStraight();
    turnGunRight(90);
    if(starta开发者_如何学Cbsolute){
        straight=true;
    }
    while (While){
        ahead(10000000);
        turnRight(90);
    }
    resume();
}

You might not understand most of the code as it extends robocode.Robot, but my problem is in the variable While. The loop doesn't end as the method gets the argument once and it is true so the method becomes an eternal loop but is there a way to refresh the method argument as I don't want to make a while loop every time I call this method?


You shouldn't write you parameters in capital letters. So it would be while instead of While. However this isn't allowed because while is a keyword. So first change your argument passed in the method.

Then your problem is, that you call the method with the argument. Since it is a primitive boolean value you pass, the value can't be changed from another method, call, class, etc. during the execution of your wallScan method and therefore the while loop never finishes.

Instead you should for example create a member field in the class containing this method an give it a meaningful way. in the example i just call it whileCondition.

void wallScan(){
    stop();
    getStraight();
    turnGunRight(90);
    if(startabsolute){
        straight=true;
    }
    while (whileCondition()){
        ahead(10000000);
        turnRight(90);
    }
    resume();
}



 public void setWhileCondition(boolean bool) {
      whileCondition = bool;
   }

   public boolean isWhileCondition() {
     return whileCondition;
   }

So you can set the condition which leads to the termination of the while loop from outside your method.


It seems to me that you don't want a single boolean value - you want something which will return you a boolean every time you ask for one. As a simple example:

public interface ContinueChecker {
  boolean shouldContinue();
}

(Horrible names, but hopefully you can come up with something better.) You can then write:

void wallScan(ContinueChecker checker) {
  ...
  while (checker.shouldContinue()) {
    ...
  }
}

An alternative form of this would be a generic interface, such as Provider<T> one from Guice:

public interface Provider<T> {
  T get();
}

Your method could take a Provider<Boolean> for the same purpose.

Personally I prefer this approach over that of Sebi - it allows your class to represent the state of the board itself (or whatever) - whether one particular robot should stop doesn't feel like it should be part of the same state. It's effectively local to this method, as far as I can see.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号