我在运行程序时遇到问题。该程序应该构造一个由墙组成的盒子,每次运行该程序时,墙应该覆盖5-10条街道/大道,并且具有不同的大小和位置。虽然有时运行它时我只会得到1条大街和街道或5条以下的东西?我想念什么?

public class CityWalls extends Thing {

public CityWalls(City c, int st, int av, Direction d) {
    super(c, st ,av ,d);

    Random rand = new Random();
    int randomNum = rand.nextInt(11);




    int oddIncrement = 0;
    if (randomNum % 2 == 0)
    {
        oddIncrement = 1;

    }


    for (int i = 0; i < randomNum; i++) { // creating the box. 7 is the placement of the robot so he appears in the middle of the box.

            new Wall(c, i+(7-randomNum/2), (7-randomNum/2), Direction.WEST);
            new Wall(c, i+(7-randomNum/2), (7+randomNum/2) - oddIncrement, Direction.EAST);
            new Wall(c, (7-randomNum/2), i+(7-randomNum/2), Direction.NORTH);
            new Wall(c, (7+randomNum/2)-oddIncrement, i+(7-randomNum/2), Direction.SOUTH);


    }

最佳答案

使用:

int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1))


代替

Random rand = new Random();
int randomNum = rand.nextInt(11);

关于java - 贝克尔机器人将墙随机化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19011133/

10-10 04:52