这可能很简单,但我只是不知道该怎么做?
我如何从类文件中重用它:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
然后使用在另一个类文件中获得的相同结果?
我的 CityWall 类(包含我要使用的 int 的类。)
public class CityWalls extends Thing {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
public CityWalls(City c, int st, int av, Direction d) {
super(c, st ,av ,d);
int oddIncrement = 0;
if (randomNum % 2 == 0)
{
oddIncrement = 1;
}
for (int i = 0; i < randomNum; i++) {
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);
}
}
public int getRandomNum() {
return randomNum;
}
}
这是我的 World Class(我想重用变量的 Class)。
public class World {
public static void main (String[] args) {
int height = 0, width = 0, top = 5, left = 5, thingCount = 20;
World b = new World();
Random rand = new Random();
// int RandomNumber = rand.nextInt(9);
CityWalls cw = new CityWalls(Gothenburg, 5 , 5, Direction.NORTH);
int RandomNumber = cw.getRandomNum();
height = (int)(Math.random() * 0.5) + RandomNumber; // I want to use the variable here.
width = (int)(Math.random() * 0.5) + RandomNumber; // And here to replace the RandomNumber. then it should be correct.
City Gothenburg = new City(16,16);
Thing[] things = ThingSpawnCity(Gothenburg, width, height, top, left, thingCount);
RobotFinder terminator = new RobotFinder(Gothenburg, 7, 7, Direction.NORTH, 0);
terminator.run();
}
public static Thing[] ThingSpawnCity(City Gothenburg, int width, int height, int top, int left, int objects){
Thing things[] = new Thing[objects];
int avenue = 0, street = 0;
for (int i = 0; i < objects; i++){
avenue = (int)(Math.random() * width) + left;
street = (int)(Math.random() * height) + top;
things[i] = new Thing(Gothenburg, street, avenue);
}
return things;
}
}