Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Intro to Java help?) Define a class named RandomWalker. A RandomWalker object s

ID: 3711110 • Letter: #

Question

(Intro to Java help?)

Define a class named RandomWalker. A RandomWalker object should keep track of its (x, y) location. All walkers start at the coordinates (0, 0). When a walker is asked to move, it randomly moves either left, right, up or down. Each of these four moves should occur with equal probability. The resulting behavior is known as a "random walk." (A 2-dimensional random walk example is pictured at right.)

Each RandomWalker object should have the following public methods. You may add whatever fields or methods you feel are necessary to implement these methods:

move()
Instructs this random walker to randomly make one of the 4 possible moves (up, down, left, or right).

getX()
Returns this random walker's current x-coordinate.

getY()
Returns this random walker's current y-coordinate.

getSteps()
Returns the number of steps this random walker has taken.

Random walks have interesting mathematical properties. For example, given infinitely many steps, a random walker approaches 100% chance of reaching a particular (x, y) coordinate. To learn more about random walks, visit http://mathworld.wolfram.com/RandomWalk.html .

Test your RandomWalker by running it with the TestRandomWalker test class, found on the Labs section of the course web site. The TestRandomWalker will run your random walker in a loop and animate its position as it moves.

Explanation / Answer

Below is your class

/*

* The class RandomWalker that contains

* methods to set x and y values of random

* walker object.

*

* */

//RandomWalker.java

public class RandomWalker {

// declare instance variables

private int x;

private int y;

private int steps;

// default constructor

public RandomWalker() {

x = 0;

y = 0;

}

// Parameter constructor to set x and y values

public RandomWalker(int x, int y) {

this.x = x;

this.y = y;

}

// Method move that generates a random number

// value in a range of 0 to 1

public void move() {

// increment the steps by 1

steps++;

// generate a random value in a range of 0-1

double rand = Math.random();

if (rand < 0.25)

++x; // move to right

else if (rand < 0.5)

--y; // move to up

else if (rand < 0.75)

--x; // move to left

else if (rand < 1.0)

++y;// move to down

}

// Returns x value

public int getX() {

return x;

}

// Returns y value

public int getY() {

return y;

}

// Returns steps

public int getSteps() {

return steps;

}

}// end of RandomWalker class