【发布时间】:2015-02-06 07:52:14
【问题描述】:
我试图用 Java 构建一个简单的 Rock-Paper-Scissors 游戏。基本上,这个想法是当玩家做出错误的举动时会被淘汰。剩下的最后一名玩家是获胜者。 我比较缺乏经验,也不太了解。我在运行时遇到了这个 ConcurrentModification 异常。我试着谷歌了一下,但没有得到任何简单的解决方法。有一些关于迭代器之类的讨论,我不太了解/理解。
我试过如下-
GameStarter 类:
public class GameStarter
{
public static void main(String[] args)
{
RPS g = new RPS();
g.play();
}
}
RPS 类:
import java.util.ArrayList;
public class RPS
{
Player p1 = new Player(" A ");
Player p2 = new Player(" B ");
Player p3 = new Player(" C ");
Player p4 = new Player(" D ");
Player p5 = new Player(" E ");
ArrayList<Integer> hold =new ArrayList<Integer>();
ArrayList<Player> active = new ArrayList<Player>();
{
active.add(p1);
active.add(p2);
active.add(p3);
active.add(p4);
active.add(p5);
}
public void play()
{
int i,j;
while(active.size()>1)
{
for(Player p:active)
{
System.out.print("\n Currently active players are: "+p.name+" , ");
}
System.out.println("\n\n");
for(Player p:active)
{
p.rpsThrow();
hold.add(p.cur);
}
if(hold.contains(1) && hold.contains(2) && !hold.contains(3))
{
for(Player p: active)
{
if(p.cur==1)
{
active.remove(p);
System.out.println("Player "+p.name+" eliminated ");
}
}
}
if(hold.contains(1) && !hold.contains(2) && hold.contains(3))
{
for(Player p: active)
{
if(p.cur==3)
{
active.remove(p);
System.out.println("Player "+p.name+" eliminated ");
}
}
}
if(!hold.contains(1) && hold.contains(2) && hold.contains(3))
{
for(Player p: active)
{
if(p.cur==2)
{
active.remove(p);
System.out.println("Player "+p.name+" eliminated ");
}
}
}
hold.clear();
try
{
Thread.sleep(3500);
}
catch(Exception ex)
{
}
}
if(active.size()==1)
{
for(Player p:active)
{
System.out.println("\n\n The winner is : \n"+p.name);
}
}
}
}
和播放器类:
public class Player
{
String name;
Integer cur;
public Player(String n)
{
name=n;
}
public int rpsThrow()
{
int t;
t=(int)((Math.random()*3)+1);
cur=t;
if(t==1)
{
System.out.println("\n"+name+" throws : rock");
}
else if(t==2)
{
System.out.println("\n"+name+" throws : paper");
}
else
{
System.out.println("\n"+name+" throws : scissors");
}
return t;
}
}
没有任何简单的方法可以解决这个 CMException 吗?请随时修改我的代码来解决它。
【问题讨论】:
-
你能发布错误吗?堆栈跟踪?
-
如何发布堆栈跟踪?
标签: java arraylist bluej concurrentmodification