2016-07-16 152 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)'。 –