java - 如何对文本使用 while 语句

标签 java loops while-loop

我正在尝试使用 eclipse 在 Java 中制作 Black Jack 的简化版本。我试图让玩家输入“击中”或“站立”,虽然他们没有这样做,但它会不断提示他们这样做。

while (hitorstand != ("hit") || hitorstand != ("stand"))
                {
                    System.out.println("Would you like to hit or stand?(1 for hit, 2 for stand)");
                    hitorstand = scan.nextLine();
                    hitorstand.toLowerCase();
                }       
                if (hitorstand.equals("hit"))
                    {
                        playercard3 = random.nextInt(10) +2;
                        System.out.println(""+playercard3);
                    }
                else if (hitorstand.equals("stand"))
                    {
                        System.out.println("You had a total value of " + playercardtotal + ".");
                        if (hiddendealercard == card2)

当我运行它时,无论我输入什么,它都无法逃脱 while 循环。我知道如果我使用数字就会起作用,但我真的想学习如何使用单词作为输入。

最佳答案

while (hitorstand != ("hit") || hitorstand != ("stand")) // This is not the right way

使用equals()方法进行字符串值比较。 == 用于对象引用比较。

while (!hitorstand.equals("hit") || !hitorstand.equals("stand")) // This is

我不知道为什么你会在 while 循环条件中使用 != ,而你已经正确使用了 (hitorstand.equals( "hit")) 位于 if 语句中 while 的下方。

此外,while 循环 block 中似乎存在一个小错误。

hitorstand.toLowerCase(); // This does nothing

由于 Java 中的字符串是不可变的,因此您需要将更改后的字符串分配回才能看到更改

hitorstand = hitorstand.toLowerCase(); // Assigning back the lowercase string back to hitorstand 

关于java - 如何对文本使用 while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455925/

相关文章:

java - HibernateTemplate.find 返回正确的行数,但数据相同

java - 如何使用 Scanner 和 while 循环进行 JUnit 测试 void 方法

c++ - 如何正确声明我的 if 或 while 语句以满足所需的输入?

java - 当我尝试使用 awt 机器人输入 java 时,什么也没输出,我做错了什么?

java - 如何在java中检测fn键按下事件

java - Avro:重用解码器

javascript - 如何使用angularJS过滤选中的复选框

python - 如何使一定长度的单词翻转?

r - 沿着从不同年份开始且具有不同窗口长度的时间序列的移动平均值

java - 当条件被 Action 监听器改变时中断 while 循环