So, my random walk program is supposed to start at coordinates 0,0 and then dependent on the value random, should + or - 1 from either x or y. If I print rand, I get a value, so it seems like its not executing the loop at all. I've tried moving rand into the loop and tried changing the for loop parameters to a few things that would ultimately result in the same goal and I cannot for the life of me seem to understand why it just doesn't output anything other than the starting coordinate (0, 0)
Any help will be greatly appreciated.
public static void main(String[] args) {
// create two variables representing x and y and set at 0
int x = 0;
int y = 0;
// define dist
int dist = Math.abs(x) + Math.abs(y);
// create instance of Math.random
double rand = Math.random();
// print starting coordinates before executing loop
System.out.print(x + ", " + y);
// for loop to count total steps taken and stop the nested loops running once absolute distance = 5
for (int total = 0; dist == 5; ++total) {
// decides if to change y or x value
//works on x
if (rand < 0.5) {
// decides if to increment or decrement x
// increments x
if (rand < 0.25) {
x++;
System.out.println(x + ", " + y);
}
// decrements x
else {
x--;
System.out.println(x + ", " + y);
}
}
// works on y
else {
// decides if to increment or decrement y
// increments y
if (rand > 0.75) {
y++;
System.out.println(x + ", " + y);
}
//decrements y
else {
y--;
System.out.println(x + ", " + y);
}
}
System.out.println("steps = " + total);
}
}
}
Aucun commentaire:
Enregistrer un commentaire