对不起,如果问题没有多大意义,我对Java很新。所以这是我的问题:我正在制作一个文本冒险游戏(目前非常基本),我创建了一个字符串(choice1),这等于玩家对游戏问题的回答。答案应该是北,北,南或南。当我发现无论我输入什么时它都说这是一个无效的答案,我让游戏显示当我输入答案时,choice1等于什么。我发现当我输入北方时,它向北显示,当我输入南方,南方等时,所以它正确地拾取了我输入的内容,但它仍然说它是无效的答案。这是我的代码(包括显示choice1等于的部分):
Scanner answer = new Scanner(in);
String choice1 = answer.nextLine();
out.println(choice1);
if (choice1 == "north" || choice1 == "North") //If the answer is North
{
out.println("You start walking towards the mountains in the distance. A cold wind picks up from behind you.");
}
else if (choice1 == "south" || choice1 == "South") //If the answer is south
{
out.println("You head into the forest and are quickly surrounded by trees. Patches of light dance on the floor to the whim");
}
else if (choice1 != "south" || choice1 != "South" || choice1 != "north" || choice1 != "North") //invalid answer
{
out.println("Please enter a valid answer.");
}
answer.close();
答案 0 :(得分:3)
使用String#equals()
代替==
来比较String
。对于不区分大小写的比较,请使用String#equalsIgnoreCase()
。
答案 1 :(得分:0)
习惯阅读文档,你不能使用==来比较字符串,如果你看一下Java的文档,你会发现方法
boolean equals(String s)
使用方法:
if(choice1.equals("whatever"))
{
// TODO the jobe here
}