我正在做一个我在互联网上发现的模拟游戏“nim”的练习。游戏的想法是让其他玩家拿起最后一个项目。我遇到的问题是在玩家1选择了哪个桩以及从该桩中拾取多少物品之后。最初工作正常,但是当它转到玩家2时,总是选择他之前的玩家堆,无论他们选择哪一堆,它都会从玩家1的同一堆中扣除他们指定的金额。这只发生在我添加了较低的 - if语句中的case选项。有人可以解释为什么它总会选择以前的球员?
while(pileA > 0 || pileB > 0 || pileC > 0){
System.out.println(playerOne+", which pile would you like to pick from?");
String choice = input.next();
System.out.println("How many cards would you like to take from pile "+choice+"?");
int amount = input.nextInt();
if(choice.equals("A") || choice.equals("a")){
pileA = pileA - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choice.equals("B") || choice.equals("b")){
pileB = pileB - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choice.equals("C") || choice.equals("c")){
pileC = pileC - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else{
System.out.println("ERROR");
}
System.out.println(playerTwo+", which pile would you like to pick from?");
String choiceTwo = input.next();
System.out.println("How many cards would you like to take from pile "+choiceTwo+"?");
amount = input.nextInt();
if(choiceTwo.equals("A") || choice.equals("a")){
pileA = pileA - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("B") || choice.equals("b")){
pileB = pileB - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("C") || choice.equals("c")){
pileC = pileC - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else{
System.out.println("ERROR");
}
}
答案 0 :(得分:1)
当您为播放器添加了两个选项时,看起来您复制了if语句并忘记将小写选项的choice.equals
转换为choiceTwo.equals
if(choiceTwo.equals("A") || choiceTwo.equals("a")){
pileA = pileA - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("B") || choiceTwo.equals("b")){
pileB = pileB - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("C") || choiceTwo.equals("c")){
pileC = pileC - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
答案 1 :(得分:0)
您正在检查player1s输入,当您应该检查小写字母输入的player2s时:
if(choiceTwo.equals("A") || choice.equals("a")){ // should be || choiceTwo.equals("a")
pileA = pileA - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("B") || choice.equals("b")){ // should be || choiceTwo.equals("b")
pileB = pileB - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
else if(choiceTwo.equals("C") || choice.equals("c")){ // should be || choiceTwo.equals("c")
pileC = pileC - amount;
System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC);
}
答案 2 :(得分:0)
错误在于
if(choiceTwo.equals("A") || choice.equals("a")){
pileA = pileA - amount;
你应该使用choiceTwo而不是第二个玩家。