我遇到了这个java问题,我想看看为它编写代码是多么容易。
编写一个Java程序,使两个人可以玩下面的游戏。我们从一堆芯片开始。你的游戏将允许奇数的数字。第一个玩家从堆中移除1到(筹码数 - 1)/ 2。从那时起,球员交替转弯,从堆中取出筹码,直到它为空。一旦堆积空了,游戏就结束了。
直到我不得不交替轮流才顺利。我做得对,但是当玩家1输入一个值,而玩家2也输入时,当while循环再次进行时,它从0开始并且不添加过去的输入。
这就是我的意思:
while(chips!=0){
if(counter%2==0){
System.out.println(fname + " has " + (one) + " chips" + "\n" + sname + " has " + (two) + " chips." + "\n" + "It is your turn, " + fname + "\n" + "There are " + chips + " remaining." + "\n" + "You may take any number of chips from 1 to " + (chips-1)/2 + ". How many will you take, " + fname + "?") ;
one +=input.nextInt();
chips -=one;
} else {
System.out.println(fname + " has " + (one) + " chips" + "\n" + sname + " has " + (two) + " chips." + "\n" + "It is your turn, " + sname + "\n" + "There are " + chips + " remaining." + "\n" + "You may take any number of chips from 1 to " + (chips-1)/2 + ". How many will you take, " + sname + "?") ;
two +=input.nextInt();
chips -=two;
}
counter++;
}
有人有解决方案吗?
答案 0 :(得分:1)
你需要增加球员的数量。按值而不是分配它。
int amount = input.nextInt();
one += amount;
chips -= amount;
答案 1 :(得分:1)
这应该有效:
import java.io.*;
import java.util.Scanner;
public class Test {
public static Scanner input;
public static void main(String[] args) {
System.out.println("Enter number of chips to start the game with:");
input = new Scanner(System.in);
int chips = input.nextInt();
turn_one(chips, 0 ,0);
}
public static void turn_one(int chips, int playerone, int playertwo){
int max;
if(chips <= 2){
max = 1;
}
else{
max = (chips-1)/2;
}
if(chips <= 0){
System.out.println("Game over!");
return;
}
System.out.println("Playerone has " + playerone + " chips" + "\n" + "playertwo" + " has " + playertwo + " chips." + "\n" + "It is your turn, " + "playerone" + "\n" + "There are " + chips + " remaining." + "\n" + "You may take any number of chips from 1 to " + max + ". How many will you take, playerone?") ;
int taken = input.nextInt();
if (taken > max){
System.out.println("You can't take that many chips!");
turn_one(chips, playerone, playertwo);
}
playerone = playerone + taken;
chips = chips - taken;
turn_two(chips, playerone, playertwo);
}
public static void turn_two(int chips, int playerone, int playertwo){
int max;
if(chips <= 2){
max = 1;
}
else{
max = (chips-1)/2;
}
if(chips <= 0){
System.out.println("Game over!");
return;
}
System.out.println("Playerone has " + playerone + " chips" + "\n" + "playertwo" + " has " + playertwo + " chips." + "\n" + "It is your turn, " + "playertwo" + "\n" + "There are " + chips + " remaining." + "\n" + "You may take any number of chips from 1 to " + max + ". How many will you take, playertwo?") ;
int taken = input.nextInt();
if (taken > max){
System.out.println("You can't take that many chips!");
turn_one(chips, playerone, playertwo);
}
playertwo = playertwo + taken;
chips = chips - taken;
turn_one(chips, playerone, playertwo);
}
}