If statement 猜谜游戏,(While循环,if语句),再次玩提示不工作
所以我对java真的很陌生,我试图通过猜谜游戏应用程序练习使用while和if语句 在我被再次邀请之前,一切似乎都很顺利。当我输入Y时,循环结束。这不应该发生,因为代码开头的while参数表示如果为true,则继续播放 我试着利用这个参数:while(答案==“Y”)。我一直在玩它,但它总是不断退出。请帮忙 代码如下:If statement 猜谜游戏,(While循环,if语句),再次玩提示不工作,if-statement,while-loop,If Statement,While Loop,所以我对java真的很陌生,我试图通过猜谜游戏应用程序练习使用while和if语句 在我被再次邀请之前,一切似乎都很顺利。当我输入Y时,循环结束。这不应该发生,因为代码开头的while参数表示如果为true,则继续播放 我试着利用这个参数:while(答案==“Y”)。我一直在玩它,但它总是不断退出。请帮忙 代码如下: import java.util.Scanner; public class GuessingGame { static Scanner sc = new Scanne
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
// TODO Auto-generated method stub
String answer = "Y";
int guess;
int number;
String again;
boolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepPlaying)
{
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = sc.nextInt();
while (guess > 10 || guess < 1)
{
System.out.print("I said, between 1 and 10. Try again: ");
guess = sc.nextInt();
}
number = (int)(Math.random() *10 + 1);
if (guess == number)
{
System.out.println("You're right!");
}
else
{
System.out.println("You're wrong! the number was " + number);
}
System.out.print("Play again? (Y or N)");
answer = sc.next();
if (answer == "Y")
{
keepPlaying = true;
}
else
{
break;
}
}
System.out.println("Thank you for playing");
}
}
import java.util.Scanner;
公开课猜谜游戏
{
静态扫描仪sc=新扫描仪(System.in);
公共静态void main(字符串[]args)
{
//TODO自动生成的方法存根
字符串answer=“Y”;
智力猜测;
整数;
再串一次;
布尔值keepPlaying=true;
System.out.println(“让我们玩一个猜谜游戏吧!”);
同时(继续播放)
{
System.out.println(“我想到的是一个介于1和10之间的数字。”);
System.out.print(“您认为它是什么?”);
猜测=sc.nextInt();
而(猜测>10 | |猜测<1)
{
System.out.print(“我说,在1到10之间,再试一次:”);
猜测=sc.nextInt();
}
number=(int)(Math.random()*10+1);
如果(猜测==数字)
{
System.out.println(“你说得对!”);
}
其他的
{
System.out.println(“你错了!数字是”+number);
}
系统输出打印(“再次播放?(Y或N)”;
答案=sc.next();
如果(答案=“Y”)
{
持续播放=正确;
}
其他的
{
打破
}
}
System.out.println(“感谢您的参与”);
}
}
在比较中,应使用字符串进行比较
要求:
if (answer.equals("Y")) // NOTE: I'd use .equalsIgnoreCase(...)
{
keepPlaying = true;
}
else
{
break;
}
还请注意,由于此比较位于循环的末尾,您可以简化为:
keepPlaying = answer.equalsIgnoreCase("Y");
由于循环将被重新计算,因此您不需要使用
break
语句。字符串不会与=
进行比较,而是与.equals()
进行比较。嘿,Kevin,非常感谢您的帮助。我很惊讶一个简单的调整就解决了这个问题。我仍然很困惑:答案==“Y”不起作用,但答案是“Y”。equals(“Y”)起作用。直觉上,它们不是一样吗?@Mike95,很高兴答案有帮助。如果合适,请接受答案。至于为什么=
不起作用,这是因为=
对于对象,测试引用相等性(即,对象是否为同一对象),而.equals()
调用该方法检查相等性。对于字符串
对象,.equals()
方法检查字符是否相同。有关更多信息,请访问。