我正在做一个学校编码项目,在其中(使用Java博士)我编写了一个石头,纸,剪刀的游戏。我的游戏会询问用户他们的投掷情况,同时随机生成计算机的投掷物。
下面的代码代表了我(不完整)确定游戏赢家的方法。应该先检查两个罚球是否相同,然后,如果不相同,则比较两个罚球以查看谁赢了。如果用户输入的答案不是石头,纸或剪刀,则最后的其他声明是备份。
当前,字符串compAnswer硬编码为“ rock”。
if (userAnswer == compAnswer)
{
System.out.println("Huh. A tie. That was... disappointing.");
win = 2;
} else if (compAnswer == "rock"){
{ if (userAnswer == "paper") {
System.out.println("Curses! I threw rock and lost!");
win = 0;
} else if (userAnswer == "scissors") {
System.out.println("Hah! I threw rock and crushed your scissors!");
win = 1;
}}
} else {
System.out.println("...You cheater! That's not a legal throw! Off to the fire and brimstone with you!");
}
但是,当我运行程序时,什么也不会打印-当userAnswer得到“纸”或“剪刀”,甚至答案是假的时候,都不会打印。我很茫然-为什么我的打印报表没有被触发?
答案 0 :(得分:0)
==
测试引用是否相等和
.equals()
测试值是否相等。
因此,请使用equals()
方法比较字符串,如下所示:
if (userAnswer.equals(compAnswer)) {}
因此您的代码将如下所示:
if (userAnswer.equals(compAnswer)) {
System.out.println("Huh. A tie. That was... disappointing.");
win = 2;
} else if ("rock".equals(compAnswer)) {
{
if ("paper".equals(userAnswer)) {
System.out.println("Curses! I threw rock and lost!");
win = 0;
} else if ("scissors".equals(userAnswer)) {
System.out.println("Hah! I threw rock and crushed your scissors!");
win = 1;
}
}
} else {
System.out.println("...You cheater! That's not a legal throw! Off to the fire and brimstone with you!");
}