2016-07-16 150 views
0

对不起,如果这个问题没有多大意义,我对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(); 
+0

根据你的代码要求,我想你想用&&而不是||对于最后的其他if语句。就你而言,如果这些条件中的任何一个将是真的,那么它将显示“无效答案”。 例如: 如果您提供“北”作为输入,它不会等于“南”,“南”或“北”,否则如果条件将导致为真,并且它将打印无效答案。 –

+0

而不是'if-else',你可以考虑一个'switch-case'。 –

回答

0

获取用于读取文档,则不能使用==比较字符串,如果你看一下Java的文档,你会发现方法

boolean equals(String s) 

如何使用:

if(choice1.equals("whatever")) 
    { 
     // TODO the jobe here 
    } 
+0

你可**使用'=='。否则,编译器不会允许你这样做。我会说你**不应该**或**不能**。 –

+0

'choice1.equals(“whatever”)'如果'choice1'为'null',将抛出'NullPointerException'。为了避免它,使用'“任何”.equals(choice1)'。 –