java - 玩简单的 Java 游戏时遇到问题

标签 java

我正在为一个类(class)编写一个程序,其中玩家和计算机正在玩游戏。游戏包括挑选 1、2、3 或 4 根火柴棍。从 21 根棍子中挑出最后一根的玩家就输了。游戏经过精心设计,以便计算机总是获胜。

无论如何,我的问题在于结束游戏的逻辑。这是我的代码:

 public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String player;
    int matchstick;
    int total = 0;

    System.out.println("Rules of the game: \nThe player and computer take turns picking 1, 2, 3 , or 4 matchsticks."
                        + " \nThe player to pick the last stick out of 21 loses.");
    System.out.print("\nHello player. Please enter your name: ");
    player = keyboard.next();

     while (total < 21) {

        System.out.print("\nHow many matchsticks do you pick, " + player + "? ");
        matchstick = keyboard.nextInt();

        while (matchstick > 4) {
            System.out.print("You have exceeded the limit of 4 matchsticks. Please try again. \n\nHow many matchsticks do you pick? ");
            matchstick = keyboard.nextInt();
        }

        total += matchstick;

        System.out.println(player + " has picked " + matchstick + " matchstick(s) and brings the total to " + total + " matchsticks.");

        if (total == 21) {
            System.out.println("You picked the last matchstick... YOU LOSE!!!");
        }

        System.out.println("\nNow it's the computer's turn.");

        if (matchstick == 1) {
            total += 4;
            System.out.println("The computer chooses 4 matchsticks, bringing the total to " + total + " matchsticks.");
        }
        if (matchstick == 2) {
            total += 3;
            System.out.println("The computer chooses 3 matchsticks, bringing the total to " + total + " matchsticks.");
        }
        if (matchstick == 3) {
            total += 2;
            System.out.println("The computer chooses 2 matchsticks, bringing the total to " + total + " matchsticks.");
        }
        if (matchstick == 4) {
            total += 1;
            System.out.println("The computer chooses 1 matchstick, bringing the total to " + total + " matchsticks.");
        }

    }

}

}

当 while 循环的条件(总计 < 21)为 false 时,如何跳过 System.out.println("You picked the last matchstick... YOU LOSE!!!"); 之后的行?有没有办法在满足条件后中断中循环?还是我的逻辑完全错误?

最佳答案

您只需从方法main返回

  ...
if (total == 21) {
     System.out.println("You picked the last matchstick... YOU LOSE!!!");
     return;
}
  ...

关于java - 玩简单的 Java 游戏时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971960/

相关文章:

java - 只从 MOQUI FrameWork 中的 restServices 返回实体的某些字段?

java - 键盘输入的最高性能

java - 如何检查 GrantedAuthority 集合中是否存在权限?

java - 从 JFileChooser Java 检索文件中的行数

java 结果确实与预期的不同

java - 如何在Swing中实现一个 "In Progress"的动画?

java - 从 Optional<Stream> 中提取流

java - 在线程 "main"java.lang.NoClassDefFoundError : org/hibernate/cache/spi/support/DomainDataRegionImpl中

java - 绑定(bind)、粘合代码和包装器库

java - 尝试通过 Selenium Webdriver 按顺序选择行时出现问题