dimanche 29 septembre 2019

How to fix this random walking program code?

I'm creating a program that generates random walking. I can't figure out why the following code is not working.

When I run it, the program doesn't proceed after asking "please enter the starting street integer: "

I tried to import Random method in my Drunkard class and then use random method in the step method. I can't figure out which part was wrong.

import java.util.Random;

public class Drunkard{
private int x;
private int y;
private int inix;
private int iniy;

public Drunkard(int avenue, int street){
    this.x = avenue;
    this.y = street; 
    this.inix = avenue;
    this.iniy = street;
}

public void fastForward(int howMany){
    int i = 0;
    while (i<howMany){
        step();
    }

}
public void step(){
    Random random = new Random();
    int ranNum = random.nextInt(4);
    if (ranNum == 0){
        this.x +=1;
    } else if (ranNum == 1){
        this.x -=1;  
    } else if (ranNum == 2){
        this.y +=1;  
    } else if (ranNum == 3){
        this.y -=1;   
    }

}
public String getLocation(){
    return x + "avenue " + y + "street";
}
public int howFar(){
    return this.x+this.y-this.inix-this.iniy;
}


}



import java.util.Scanner;

public class DrunkardTester {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please enter the starting avenue integer: ");
int avenue = input.nextInt();
System.out.println("Please enter the starting street integer: ");
int street = input.nextInt();

// make the Drunkard with initial position
Drunkard ozzy = new Drunkard(avenue,street);

// have him move 100 intersections
ozzy.fastForward(100);

// get his current location
String location = ozzy.getLocation();

// get distance from start
int distance = ozzy.howFar();

System.out.println("Current location: " + location);
System.out.println("That's " + distance + " blocks from start.");

}
}



Aucun commentaire:

Enregistrer un commentaire