锁定用户输入并计算循环发生的时间

Locking user input and counting amount of time loop happens

我是新手,如果我有点困惑,请见谅

所以这是我的代码,它是一个基于 2 名玩家将 1 或 2 添加到变量 "counter" 的游戏,将最后的 1 或 2 添加所有数字直到 21 的人获胜。

所以我想得到帮助的是,我想将用户输入锁定为只能 select 1 或 2,不能输入任何其他内容,因为那样会违反游戏规则。我也想有一种方法来确定谁赢了,玩家 1 或玩家 2。比如计算循环发生的次数,这样我就可以区分玩家 1 或 2 是一个。

如有任何帮助,我们将不胜感激!谢谢!

package hemtenta;
import java.util.Scanner;

public class Hemtenta {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    int addcounter = 0;
    int sum;
    System.out.println("Welcome to 21");
    System.out.println("The game revolves about you or your opponent getting to 21 ");
    System.out.println("You both start on the same number 0, ");
    System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
    System.out.println("Think smart!");

    while(counter <= 20) { 
      System.out.println("Please choose to add 1 or 2");
      addcounter = input.nextInt();
      counter += addcounter;

      System.out.println("We are now on a total of " + (counter));
    }
    if (counter==21) { 
      System.out.println("Congratulations x! you won");
    } 
    else { 
      System.out.println("Something went wrong! Try again");
    }
  }
}

您可以考虑添加一个

while (addcounter != 1 && addcounter != 2) {
    // Prompt for values
}

检查用户输入的值是1还是2。如果不是,则不接受并继续提示,直到注册有效输入。

还有一个

int turnCounter = 0;
...
// Within the loop
turnCounter += 1;
...
// At the end
if (turnCounter % 2 == 0) {
    //Player Y wins
} else {
    //Player X wins
}

为了确定回合,因为第 1 回合将由玩家 X 进行,而第 2 回合将由玩家 Y 进行。玩家 Y 的所有回合将是 2 的倍数。