从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]= "
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可用选项:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
...
List 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,arrays
来源: https://codeday.me/bug/20190627/1304571.html