java重用来自不同类的变量?
这可能很简单,但我就是不知道怎么做
如何从类文件中重用此文件:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
然后使用在另一个类文件中获得的相同结果
My 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;
}
}
这是我的世界类(我希望重用变量的类)
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;
}
}
# 1 楼答案
您需要对要使用的类的实例的引用。您需要访问要在该类中使用的字段。e、 g
# 2 楼答案
在你的课堂上为它添加一个getter并将其公开
编辑
包含随机数的类:
另一个想要访问随机数的类
编辑2
第一步
在构造函数之外,使
randomNumber
成为类CiytWalls
的成员变量其次,将getter添加到
CityWalls
然后在main中将构造函数调用的结果分配给一个局部变量
之后,您可以访问使用以下方法创建的CityWalls对象的随机数:
# 3 楼答案
阅读一下
encapsulation
和getters and setters
,你可以这样做:# 4 楼答案
您可以通过将成员变量randomNum作为类CityWalls的静态变量来实现。并将该变量用于您的世界类。通过这样做,您将获得与城市墙类中指定的值相同的值。但是您实际上想要重用,或者我会说使用具有相同名称的变量&;如果您不想为它分配内存,或者出于任何其他原因,您发现它对您的案例有用,那么您应该将城市墙类扩展到您的世界类
希望这澄清了你的疑问