Note that there are some explanatory texts on larger screens.

plurals
  1. POProgram using loops and random generator (beginning java)
    primarykey
    data
    text
    <p>A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. Represent locations as integer pairs (x,y). Implement the drunkard's walk over 100 intersections, starting at (0,0) and print the ending location</p> <p>Can anyone help? I'm completely lost with using random generators and loops in the same program</p> <p>Below is what I have. It complies fine but doesn't print anything and I'm not sure if I got the random 100 intersection thing right </p> <pre><code>import java.util.*; class Drunkard { int x, y; Drunkard(int x, int y) { this.x = x; this.y = y; } void moveNorth() { this.y -= 1; } void moveEast() { this.x += 1; } void report() { System.out.println("Hiccup: " + x + ", " + y); } } class Four { public static void main(String[] args) { Random generator = new Random(); Drunkard drunkard = new Drunkard(100, 100); int direction; for (int i = 0; i &lt; 100; i++) { direction = Math.abs(generator.nextInt()) % 4; if (direction == 0) { // N drunkard.moveNorth(); } else if (direction == 1) { // E drunkard.moveEast(); } else if (direction == 2) { // S System.out.println("Should move South."); } else if (direction == 3) { // W System.out.println("Should move West."); } else { System.out.println("Impossible!"); } System.out.drunkard.report(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload