![](/img/trans.png)
[英]How to search an array of instance variables inside an array of objects in Java?
[英]how to access variables in objects in an array of objects in java
我正在研究android中的游戲開發
我的模型包里有一個名為droid的類,我的主游戲面板類中有一個名為update()的構造函數
我想制作一系列機器人並在我的主游戲面板和主游戲面板類中的構造函數中訪問它們。 我可以從主游戲面板構造函數執行此操作,但不能從更新構造函數執行此操作。 即每當我嘗試訪問主游戲面板類的更新構造函數中的某個機器人的x位置時,我會收到此錯誤:“表達式的類型必須是數組類型,但它已解析為Droid”
package net.test.droid.model;
public class Droid {
private Bitmap bitmap; // the actual bitmap
private int x; // the X coordinate
private int y;
private boolean touched; // if droid is touched/picked up
public Droid(Bitmap bitmap, int x, int y) {
this.bitmap = bitmap;
this.x = x;
this.y = y;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x, y, null);
}
}
在主要游戲中
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
public Droid droid_array;
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
Droid[] droid_array = new Droid[5];
for (int i = 0; i < 5; i++) {
droid_array[i] = new Droid(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher), droid_x_pos + i*10, droid_y_pos);
}
droid_array[1].setX(666);
}
最后一行工作正常但是當我嘗試在update()中使用它時,我得到了錯誤
public void update() {
test=droid_array[1].getX();
}
上面的行返回錯誤“表達式的類型必須是數組類型,但它解析為Droid”
這是你的問題:
public Droid droid_array;
有類型Droid
。 這是您的類級屬性。 在MainGamePanel
構造函數中,您使用此變量隱藏類級屬性:
Droid[] droid_array
離開MainGamePanel
構造函數后, Droid[] droid_array
變量超出范圍。
Update方法引用public Droid droid_array
類屬性,該屬性不是數組。
基本上,有兩個名為droid_array
變量。
public Droid droid_array; //this is of type Droid
Droid[] droid_array = new Droid[5]; //this is an array of Droid type
在MainGamePanel(Context contect)
構造函數的最后一行, droid_array
可以作為數組訪問,因為droid_array
是方法范圍。
但是在update()
方法中,沒有像droid_array
這樣的數組。 這使得Droid droid_array
在那里可用,它不是數組而是Droid
類型的對象。
你需要做這樣的事情。
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
public Droid[] droid_array;
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
droid_array = new Droid[5];
for (int i = 0; i < 5; i++) {
droid_array[i] = new Droid(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher), droid_x_pos + i*10, droid_y_pos);
}
droid_array[1].setX(666);
}
public void update() {
test=droid_array[1].getX();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.