java - 程序加 1、2 或 3,直到达到 21

标签 java loops if-statement for-loop do-while

我正在制作一个名为“count 21”的程序。它的工作原理是:“两个人玩计数 21 的游戏,轮流输入 1、2 或 3,即 添加到运行总计中。增加数值使总数超过的玩家 21 输掉了比赛。创建一个计数 21 的游戏,其中玩家与 计算机,并编写一个始终能让计算机获胜的策略。任何 回合中,如果玩家输入的值不是 1、2 或 3,则强制玩家重新输入 值(value)。” 我无法弄清楚应该如何执行此操作,这就是我到目前为止所拥有的:

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Count21 {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int x; //running total
    int y; //input num
    String strInput = "";
    String message = "";
    String answer = "";

    do {
        strInput = JOptionPane.showInputDialog(null, "Welcome to Count 21. \n In this game you will play against "
            + "the computer and add the numbers 1, 2, or 3 together. \n Whoever pushes the "
            + "numbers over 21 loses. \n Do you want to add 1, 2, or 3? "
            + "(please enter the number you choose.");
        y = Integer.parseInt(strInput);
        x++; 
        if (y == 1) {JOptionPane.showMessageDialog(null, "You chose the number 1."
            + " 1 will be added to the running total of" + (x + 1) +" .");
        }
        else if (y == 2) {JOptionPane.showMessageDialog (null, "You chose the number 2."
           + "2 will be added to the running total of" + (x + 2) + " .");
        }
        else if (y == 3) {JOptionPane.showMessageDialog (null, "You chose the number 3."
            + "3 will be added to the running total of" + (x + 3) + " .");
        }
        else{ 
            JOptionPane.showMessageDialog(null, "You didn't type a valid number, please try again. \n");
       }
    } while (x > 21);
}
}

程序运行并且用户输入他们选择的数字后,程序结束。到目前为止,这就是我所拥有的一切,但我一直困惑于如何让用户添加的数字保持在 21 之前。我也不确定如何让计算机赢得游戏。我想我应该使用 for 循环? 非常感谢任何建议或意见。如果我的代码或问题不清楚,我深表歉意。

最佳答案

正如评论中所建议的,您不应该增加 x每次输入值时加一。这还会导致进一步的问题,因为当输入无效数字时,它仍然会增加。相反,您应该检查 y 的值然后在条件逻辑(IF 语句)中添加适当的金额。这还应该简化逻辑中包含的输出消息,因为在打印 x 时您不需要向 x 添加任何内容。

同样,正如评论中所述,while 条件应该是 x < 21 .

关于java - 程序加 1、2 或 3,直到达到 21,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168647/

相关文章:

jQuery 循环动画每次都会暂停。如何避免停顿?

python - 列表理解和循环之间的区别

javascript - if-else JavaScript 不工作

javascript - 使用 JavaScript 的浏览器密码主页

java - 在 Liberty Server 上运行 spring-boot 应用程序

java - 如何在匿名类中访问变量?

java - 如何使用 Google Guice 将一个实现绑定(bind)到几个接口(interface)?

Java嵌套for循环

c++ - 我将如何使用调用相同构造函数的静态成员函数创建两个矩阵(所有值为 Ones 或值 Zeros)?

Java 单例和同步