从 C 转移到 Java 后,我了解到 Java 包含许多可以为您完成工作的函数,可以这么说,不像在 C 中您必须手动执行操作。
我目前正在设计一个 OOP 棋盘游戏,允许多个玩家选择一个棋子,在整个游戏中代表他们。我把棋子存储在一个数组中,然后问玩家的数量来挑选一个棋子。然而,出于显而易见的原因,他们不允许选择与他们之前的玩家相同的棋子。因此,我的问题是有一个功能可以让我从阵列中删除一个被选中的棋子,或者我必须手动这样做,可以这么说。如果需要,我的代码如下:
String[] potential_player_pieces = new String[10]; // Array storing the playing pieces available
potential_player_pieces[0]= "*";
potential_player_pieces[1]= "|";
potential_player_pieces[2]= "?";
potential_player_pieces[3]= "@";
potential_player_pieces[4]= "&";
potential_player_pieces[5]= "¬";
potential_player_pieces[6]= "!";
potential_player_pieces[7]= "%";
potential_player_pieces[8]= "<\n";
String[] player_pieces = new String[players+1]; // String to store the playing pieces that the players have chosen
for (int i=1; i<=players; i++) // Loops to the number of players and asks them what playing piece they want
{
System.out.print("Player " + i + " pick a playing piece:"); // Asks the players the question
for (int j=0; j<=8; j++){
System.out.print(potential_player_pieces[j]); // Displays the possible playing pieces
}
player_pieces[i] = reader.nextLine();//Saves the player chioces to the array made above
}
最佳答案
我会介绍一个新的 List<String>
当前玩家的可用选项:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
...
List<String> availableOptions = new ArrayList<>(
Arrays.asList(potential_player_pieces)
);
并在选择完成后删除选择的元素:
for (int i = 0; i < players; ++i) {
System.out.println("Player " + i + " pick a playing piece: " + availableOptions);
availableOptions.remove(player_pieces[i] = reader.nextLine());
}
您还可以将数组的初始化缩短为:
String[] potentialPlayerPieces = new String[] {"*", "|", ..., "<"};
请注意,我已将变量重命名为看起来更Javaish。
关于java - 在 Java 中的循环中从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49706017/