【发布时间】:2016-07-08 04:28:15
【问题描述】:
我想搜索二维对象数组并根据对象类字段分别测试 1 和测试 2 分离对象。然后我想将 2d 数组的对象索引写入两个 1d 数组作为 x,y。我想为每个对象有两对两个一维数组,以便我可以计算测试 1 和测试 2 对象之间的距离。
我的问题/问题 当我在其中一个 1d 数组上运行循环以打印它们的值以检查它们时,它们填充了一堆零,它们不应该是。我在代码中包含了 cmets 以帮助澄清。
public class gameboard2 {
public static void main(String[] args) {
Character2 objectArray[][] = new Character2[8][8];
int test1X1[] = new int[100];
int test1Y1[] = new int[100];
int test2X2[] = new int[100];
int test2Y2[] = new int[100];
int junkX1Array[] = new int[100];
int junkY1Array[] = new int[100];
for (int row = 0; row < objectArray.length; row++){
for(int col = 0; col < objectArray.length; col++){
if (row <= 1 && col <= 7){
objectArray[row][col] = new Character2();
objectArray[row][col].setType("Test1");
objectArray[row][col].setIdTest1(row,col);
objectArray[row][col].objectFlag = true;
}
else if ((row == 6 || row == 7) && (col <= 7)){
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test2");
objectArray[row][col].setIdTest2(row,col);
objectArray[row][col].objectFlag = true;
}
else {
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test3");
}
}
}
for (int x = 0; x < objectArray.length; x++){
for (int y = 0; y < objectArray.length; y++ ){
if (objectArray[x][y].getType().compareTo("Test1") == 0){
test1X1[x] = x;
test1Y1[y] = y;
}
if (objectArray[x][y].getType().compareTo("Test2") == 0){
test2X2[x] = x;
test2Y2[y] = y;
System.out.println(test2X2[x]);
//Arrays are filled with 2d array object indices and printed as they are filled. These values appear correct. However when you print from the array (see below) its filled with a bunch of zeros.
}
else
junkX1Array[x] = x;
junkY1Array[y] = y;
}
}
System.out.print("Now the newly created array will be printed");
// Array is printed. Values differ.
for (int b = 0; b < test2X2.length; b++)
{
System.out.println(test2X2[b]);
}
}
}
// 这是对象类。
public class Character2 {
private String id;
private String type;
boolean objectFlag = false;
public void setType(String AssignType) {
type = AssignType;
}
public String getType(){
return type;
}
public String getId(){
return id;
}
public void setIdTest1(int row, int col){
id = ("Test1" + " row: " + row + " col: " + col);
}
public void setIdTest2(int row, int col){
id = ("Test2" + " row: " + row + " col: " + col);
}
}
【问题讨论】:
-
你的objectArray中的行数和列数是否相等?
-
是的,它是 8 x 8 字符 objectArray[][] = new Character[8][8];
-
你有什么问题?
-
我想在我的二维对象数组中找到对象的索引并将它们分别保存到一维数组x和y中,这样我就可以计算它们之间的距离了。
-
@BurtReynolds 没关系。您具体要问我们什么?
标签: java arrays multidimensional-array