申し訳ありませんが、質問があまり意味がない場合は、私はJavaにとって非常に新しいです。それでは私の問題は次のとおりです。私はテキストアドベンチャーゲーム(現時点では非常に基本的です)を作っていて、ゲームが尋ねる質問にプレイヤーが与える答えと同じ文字列(choice1)を作成しました。答えは、北、南、南、南のいずれかとします。私が入力した内容が無効な回答であっても、答えを入力したときのchoice1と同じものをゲームに表示させました。私が北に打ち込んだとき、北、南、南などを打ったときにそれが表示されたことを知ったので、それは正しくタイプされましたが、それはまだ無効な答えだと言いました。ここで(に等しいものをchoice1表示する部分を含む)私のコードは次のとおりです。(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();
あなたのコード要件に従って、私はあなたが||の代わりに&&を使いたいと思います。最後のelse if文のために。あなたのケースでは、それらの条件のいずれかが真である場合、「無効な回答」と表示されます。 例: 入力として「北」を入力すると、「南」、「南」または「北」と等しくなくなり、条件が真となる場合は無効な回答が印刷されます。 –
'if-else'の代わりに' switch-case'と考えることができます。 –