java - while 循环内的 if/else 语句

标签 java if-statement while-loop

我编写了一个游戏代码,模拟用户和计算机掷骰子,获胜者从失败者那里获得 1 美元,每人从 2 美元开始。代码运行良好,但当用户或计算机达到 0$ 时,它不会像我预期的那样结束。有什么建议吗?

import java.util.Scanner;

public class ALE_04_RollDice {
public static void main (String[] args) {

    Scanner input = new Scanner(System.in);
    int userMoney = 2;
    int compMoney = 2;
    int userRoll = (int) (1 + Math.random() * 6);
    int compRoll = (int) (1 + Math.random() * 6);

    System.out.print("Press 'r' if you would like to roll ");
    do {String roll = input.nextLine();
    if (roll.equals("r")); {
        if (userRoll > compRoll){
            userMoney++;
            compMoney--;
     System.out.print("The computer rolled " + compRoll + " and you rolled "       + userRoll + ". you won."
        + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
            }

            else if (userRoll < compRoll) {
                compMoney++;
                userMoney--;
                System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + 
                        ". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
            }

            else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll + 
                    ". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}


            }
            }while (userMoney >= 0 || compMoney >=0);
    }}

最佳答案

您的 while 语句正在测试 <= 0,但最初两个变量都 > 0。 while 循环永远不会触发。

关于java - while 循环内的 if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271066/

相关文章:

java - 为什么初始化字符串后得到 null?

java - 我想在 Selenium 中按类抽象

c++ - C 预处理器和 if-else 条件语句

mysql - 如果条件在 mysql 查询中

java - 为什么我的迭代器remove()方法没有删除任何东西?

java - 需要帮助在 java 中循环我的 try 和 catch 语句

java - 与 Android 线程、Handler 和 HandlerThreads 的并发

java - 如何将 sun.misc.BASE64Encoder 转换为 org.apache.commons.codec.binary.Base64

jsp - 如果...其他...在 JSP 中。我的代码有什么问题?

c - 使用 Read 系统调用时,While 循环不会退出