【发布时间】:2014-02-01 23:58:02
【问题描述】:
我无法正确输出。基本上,我正在编写一个基本的搜索游戏,我的程序有多维字符数组(每个索引都被初始化为一个空格'')。有 2 名玩家轮流猜(输入 2 个数字,用空格隔开),如果玩家 1 猜错了,则将 '1' 存储到该字符数组中;如果玩家 2 猜错了,那就是 2。但是当他们中的一个猜对时,它会显示他们的数字加上已经存储在该 char 数组中的 char 'P'(例如:1P 或 2P)(我使用随机类来随机化要搜索的对象的位置)。我已经完成了所有工作,只是我真的不知道如何在 char 数组的同一索引中显示玩家编号和“P”。我知道我们不能有 2 个字符,因为它是字符。
这是从我的代码运行的示例(我实际上尝试过,但它显示一个“?”):
这是当其中一个玩家找到“P”时我想得到的输出:
这是我在 toString() 方法中使用输出数组时的代码:
for(int top = 0; top < totalRooms * 2; top++) {
a+= "__";
}
for(int row = hidingPlaces.length - 1; row >= 0; row--) {
a += "\n";
for(int col = 0; col < hidingPlaces[row].length; col++) {
a += "| " + hidingPlaces[row][col] + " ";
}
a += "|\n";
for(int bot = 0; bot < hidingPlaces[row].length; bot++) {
a += "|___";
}
a += "|";
}
这是我用播放器#初始化字符数组的代码:
public boolean searchRoom(int floor, int room, char players) {
if (hidingPlaces[floor][room] != hidingPlaces[floorLocation][roomLocation]) {
hidingPlaces[floor][room] = players; // fill out those empty spots in the array with players' index
aArray[floor][room] = players; // samething here, except that this array doesn't show 'P'
found = false;
} else {
winner = players; // char winner is now the players' index.
found = true;
}
return found;
}
//output this array if puppy is found.
for(int top = 0; top < totalRooms * 2; top++) {
a+= "__";
}
for(int row = hidingPlaces.length - 1; row >= 0; row--) {
a += "\n";
for(int col = 0; col < hidingPlaces[row].length; col++) {
a += "| " + hidingPlaces[row][col] + " ";
if(hidingPlaces[row][col] == '3') {
a += "1P";
} else if (hidingPlaces[row][col] == '4') {
a += "2P";
}
}
a += "|\n";
for(int bot = 0; bot < hidingPlaces[row].length; bot++) {
a += "|___";
}
a += "|";
}
}
return a;
【问题讨论】:
-
事实上,我能想到的将玩家编号 + P 放在同一个单元格中的唯一方法与字符串有关?如果是这样,有没有办法将二维字符数组转换为字符串数组?
-
有什么理由不能用 3 存储 1P 寻找小狗, 4 存储 2P 寻找小狗?如果没有,那么您可以在输出循环上使用一个条件(如果它等于 3 个输出“1P”)
-
我回滚了您的编辑。提问后您无法删除该问题,这对其他人来说毫无用处。请不要再次尝试删除它。
标签: java arrays string multidimensional-array char