package randomWalk;

import java.util.Random;
import java.util.Scanner; public class RandomWalk { public static void main(String[] args) { Scanner console = new Scanner(System.in);
System.out.print("intput the steps you want to walk:");
int steps =console.nextInt();
randomWalk(steps); }
public static void randomWalk(int steps)
{
System.out.println("walking " + steps + " steps" ); Random r =new Random(); int position =0,max = position;
int direction = 0;
for(int i = 0;i< steps;i++)
{
direction = r.nextInt(2);
if(direction == 1)
position += 1;
else
position -= 1;
if(position > max)
max = position;
System.out.println("position = " + position);
}
System.out.println("max postion = " + max);
}
}

结果类似于:

intput the steps you want to walk:7
walking 7 steps
position = 1
position = 0
position = -1
position = -2
position = -3
position = -2
position = -1
max postion = 1

04-28 04:04