我正在尝试使用 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/