This is a program i'm stuck on for school. Can't figure out why it won't give me a average and a greatest. The program runs 50 times like i want it to but does not add a value to moves and total.
import java.util.*;
public class RandomWalk {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
int location;
double average;
int greatest=0;
int moves = 0;
int total = 0;
int step;
for (int i = 0; i < 50; i++) {
location = 4;
step = rand.nextInt((2 - 1) + 1) + 1;
while (location < 1 || location > 7) {
moves ++;
if (step == 2){
location ++;
} else {
location --;
}
if (moves > greatest) {
greatest = moves;
total += moves;
}
}
}
average = total / 50;
System.out.println("The greatest number of steps: " + greatest);
System.out.println("The average number of steps: " + average);
}
}
fixed the for loop but it still does not give me the average and the greatest.
as for the while (location < 1 || location > 7)
it should run till the person stands on location 1 or location 7.
here is the problem i was given:
In the "random walk", a person is placed at the center of a seven meter long bridge. Each step moves a person 1 meter either forward or backward at random. Create a randomwalk that determines how many steps the person will walk before taking a step off the bridge. Have the application average 50 trials, and display the average and the greatest number of steps.
thanks for helping...
if i change it to this: `import java.util.*;
public class RandomWalk2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
double average;
int greatest=0;
int moves;
int total = 0;
int step;
step = rand.nextInt((2 - 1) + 1) + 1;
int location; //location of man on bridge
for(int i = 0; i < 50; i++)
{
moves = 0;
moves++;
location = 4;
total += moves;
while(true)
{
if (step == 2) {
location++;
} else {
location--;
}
if((location < 1) || (location > 7)) break;
}
if(moves > greatest) {
greatest = moves;
}
}
average = total / 50;
System.out.println("The greatest number of steps: " + greatest);
System.out.println("The average number of steps: " + average);
}
}
` then it runs 50 times but the guy only moves 1 stop so my greatest and average always shows as 1.