This is a very simple Java code and I want to write a code that counts how many times the step method is called. Essentially, this code will draw a blob and count how many "steps" the blob takes. If the step number is equal to the Max, then the blob will take a new dx/dy eg a new velocity.
The Blob class is not that important, so I didn't attach it. However, the PurposefulWanderer class is called by another class, specifically a GUI
I tried making a static variable called current and I increment it by one under the step method, but this isn't working. It still says that the current variable is still 0.
public class PurposefulWanderer extends Blob {
private int TOTAL;
private static int current = 0;
public PurposefulWanderer (double x, double y) {
super (x, y);
this.TOTAL = (int) (Math.random()*10)+10;
}
@Override
public void step() {
++current;
// Choose a new step between -1 and +1 in each of x and y
if (current == this.TOTAL)
dx = 2 * (Math.random()-0.5);
dy = 2 * (Math.random()-0.5);
x += dx;
y += dy;
current = 0
}
}
if (current == this.TOTAL)
dx = 2 * (Math.random()-0.5);
dy = 2 * (Math.random()-0.5);
x += dx;
y += dy;
current = 0
Your code lacks curly braces after the if-statement. The if-statement now applies only to the first line after it. Everything else is executed every time the method is called. Including the line that sets current to zero.
I guess you added the static
qualifier there when trying to get this work? :) You can remove it now. It causes the variable to be shared with all instances of PurposefulWanderer
, causing bugs when you have more than one.
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.