java 循环清除数组_使用Java从循环中的数组中删除元素

从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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值