[英]How to get array of object of object and their response using setter and getter method
[英]How can I create a getter method and a setter method for a multidimensionnal array?
首先,对不起我的英语,我是法语。
这是我要通过用数学符号编写此问题来解决的问题:
我有几个看起来像这样的坐标: (x, y)
An = {(Xn;Yn)}
array[An][(Xn;Yn)] = {{X1;Y1}{X2;Y2}...{Xz;Yz}};
在我的程序中,我需要为多维数组创建一个getter和setter方法。
这是我的代码:
//Infos for animations of objects
//Sorting
Random random1 = new Random();
int obscMin=0, obscMax=4; //I sort them to know how many obstacles will have to be created. obsc is the obstacle
int nbreObsc = obscMin + random1.nextInt(obscMax - obscMin); //nbreObsc is the number of obstacles
//End of sorting
/*Here's the model of a table:
A couple: An={(Xn;Yn)}
Tableau1[An][(Xn;Yn)]={{X1;Y1}{X2;Y2}...{Xz;Yz}};*/
float posObsc [] []=new float [nbreObsc] [2]; //New table, which will contain the positions of the obstacles
//Obstacle position getter and setter
public float[][] getPosObsc(){//getters
return posObsc;
}
public void setPosObsc(float[][] posObsc){//setters
this.posObsc=posObsc;
}
//End of obstacle position getter and setter
protected boolean detruireObsc=false; //"detruireObsc" means "destroyObstacle"
//Algorithm that defines the movement of obstacles
protected void obscDeplacemt(){
for(int i=1;i<=nbreObsc;i++){
//Sorting to determine the Xs
float ordMin=0,ordMax=width;
float ordObsc = ordMin + (float)Math.random() * (ordMax - ordMin); //ordObsc means obstacleXPosition
setPosObsc( posObsc [i][0]);
//End of sorting
}
}
//End of obstacle movement algorithm
这是我从日食中得到的错误:
The method setPosObsc(float[][]) in the type Activity01Jeux.RenderViewJoueur is not applicable for the arguments (float)
代码行:
setPosObsc( posObsc [i][0]);
正在使用数组数组中的单个float
元素调用setPosObsc()
方法。 但是该方法需要一个数组数组。
为了使代码编译,您可以编写:
setPosObsc(posObsc);
虽然那可能不是您想要的! 如果您尝试编写一个在特定点将浮点数放入数组的方法,则将需要以下内容:
void setObstacleAt(int obstacleIndex, int boundaryIndex, float shiftDistance) {
posObsc[obstacleIndex][boundaryIndex] = shiftDistance;
}
我正在对数组包含的内容进行疯狂的猜测。
作为附带说明,您可以考虑使用更长或更精确的方法名称而不使用缩写,而不是编写注释来解释方法名称。 在Java中,变量和方法名称的长度没有实际限制。
顺便说一句,做得很好,因为它不是您的母语时,有勇气用英语写给StackOverflow。 即使在Runemoro进行编辑之前,我也能轻松理解您的问题。
您的getter和setter方法很好。 该错误是因为在obscDeplacemt()的最后一行代码中,您正在调用setPosObsc(posObscp [i] [0])。 当您的setter方法需要参数中的float数组以使其起作用时,posObscp [i] [0]将为您提供float。 祝好运!
看来您要执行的操作是:
posObsc[i][0] = ordObsc;
如果您处于同一班级,则无需使用setter。
如果您希望能够通过索引从外部设置元素值(而不是覆盖整个数组),则有两种解决方法:
1)(不推荐)
由于您要在吸气剂中暴露整个阵列,因此理论上您可以调用
getPostObsc()[i][0] = ordObsc;
2)(推荐)
将您的getter和setter更改为
public float getPosObsc(int x, int y){
return posObsc[x][y];
}
public void setPosObsc(int x, int y, float val){
this.posObsc[x][y] = val;
}
现在,您可以使用带有索引的设置器来更新元素:
setPostObsc(i, 0, ordObsc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.