【问题标题】:Locking user input and counting amount of time loop happens锁定用户输入并计算时间循环量
【发布时间】:2016-03-03 03:57:58
【问题描述】:

我是新手,如果我有点困惑,很抱歉

这是我的代码,它是一款基于 2 名玩家的游戏,将 1 或 2 加到变量“计数器”中,最后一个 1 或 2 将所有数字加到 21 获胜。

所以我想得到帮助的是我想锁定用户输入,使其只能选择 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");
    }
  }
}

【问题讨论】:

  • 从用户那里获取输入,使用'if condition'检查,如果为真则获取输入,否则就中断。

标签: java if-statement while-loop counter


【解决方案1】:

你可以考虑添加一个

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 的倍数。

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多