Search code examples
javacounteralternating

alternating players and adding user inputs


I came across this java question and I wanted to see how easy it would be to write the code for it.

Write a Java program that enables two people to play the following game. We start with a pile of chips. Your game will allow for numbers that are odd. The first player removes between 1 and (number of chips - 1) / 2 from the pile. From then on the players alternate turns, removing chips from the pile until it is empty. Once the pile becomes empty, the game is over.

It was going well till I had to alternate turns. I did it right but when player 1 puts in a value, and player 2 does too, when the while loop goes again, it starts at 0 and not adding the past inputs.

This is what I mean:

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++;
}

Does anyone have a solution for that?


Solution

  • You need to increment the players' chips by a value instead of assigning it.

    int amount = input.nextInt();
    one += amount;
    chips -= amount;