对不起,如果这个问题没有多大意义,我对Java很陌生。所以这是我的问题:我正在制作一个文本冒险游戏(目前非常基本),并且我创建了一个字符串(choice1),这与玩家对游戏提出的问题的回答相同。答案要么是北,北,南或南。当我发现无论我输入什么内容时都说这是一个无效的答案,我让游戏展示了当我输入我的答案时,我的选择等于什么。我发现,当我输入北方时,它显示北方,当我输入南方,南方等时。因此,它正确地拾取了我输入的内容,但仍然表示它是无效的答案。这里是我的代码(包括显示什么选择1等于部分):(Java)If和else if语句不能识别字符串
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();
根据你的代码要求,我想你想用&&而不是||对于最后的其他if语句。就你而言,如果这些条件中的任何一个将是真的,那么它将显示“无效答案”。 例如: 如果您提供“北”作为输入,它不会等于“南”,“南”或“北”,否则如果条件将导致为真,并且它将打印无效答案。 –
而不是'if-else',你可以考虑一个'switch-case'。 –