早上好,
我有一个小问题。 我创建了一个名为Map()的类。在这个类中有一个生成数组的方法。然后我创建了另外两个扩展Map的类(Top和Bottom)。然后我创建了2个对象。顶部和底部之一。我想为Top的对象和Bottom的对象获取相同的数组。这是代码来源:
public class Map{
public Map(){}
public int [] yTopValues()
{
int [] arrayTopY = new int[100];
for(int i=0;i<100;i++)
arrayTopY[i]=randomInt(-50,50);//it puts in i-th position an int between 50 and -50
return arrayTopY;
}
public int [] yBottomValues()
{
int [] arrayBottomY = yTopValues;
for(int i=0;i<100;i++)
arrayBottomY[i]=arrayBottomY[i]-250;
return arrayBottomY;
}
public int [] xValues()
{
int [] arrayX = new int[100];
for(int i=0;i<100;i++)
arrayX[i]=randomInt(0,50);//it puts in i-th position an int between 0 and 50
return arrayX;
}
//other stuff
}
public class TopMap extends Map{
public TopMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yTopValues,
200)
);
}
public class BottomMap extends Map{
public BottomMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yBottomValues,
200)
);
}
在View类中,我创建了两个对象,一个是TopMap,另一个是BottomMap,然后我用 g2.draw(topMap.area)和 g2.draw(bottomMap.area)绘制了区域。 )
我需要2个多边形相似,但它们都不同,因为该方法执行了两次。我该怎么办? 非常感谢!!
答案 0 :(得分:0)
类Map不包含数组。它只对xValues()方法是局部的。如果你想让其他类得到那个确切的数组:
/*
* Since this is a variable in the CLASS field, this object will
* be accessible to the child class.
*/
private int[] arrayX = new int[100];
public Map(){
createArrayX(); // This makes sure that the array is created, or else
// every value inside of it will be 0.
}
public void createArrayX(){ // Exact same thing as xValues(), but without the return type
for(int i=0;i<100;i++){
arrayX[i]=randomInt(0,50);
}
}
public int[] getArrayX(){ // The method that gets the array.
return arrayX;
}