2013-04-11 25 views
0

所以我一直有.toLowerCase的問題,我已經檢查了大量的文章,視頻和書籍的工作原理。我試圖做一個愚蠢的遊戲作爲我的朋友的笑話,顯然這不會工作如何在這種特殊情況下使.toLowerCase工作..似乎根本不工作

什麼是解決它的最好方法,以及如何.toLowerCase()的工作?如果可以給出一個簡單的解釋,我會非常高興! :)

「選擇」是一個靜態字符串。

public static void part1() 
     { 
      System.out.println("Welcome to Chapter ONE "); 
      System.out.println("This is just a simple Left Right options."); 
      System.out.println("-------------------------"); 
      System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area."); 
      choice = input.next(); 
      if(choice.toLowerCase()=="left") 
      { 
       deathPre(); 
      } 
      else if(choice.toLowerCase()=="right") 
       { 
        TrFight(); 
       } 
      } 

所以這是它不起作用的部分(是的,這是第一部分諷刺)我已經嘗試了其他方法來使這項工作。儘管這對我來說最簡單的做法突然變得不可能。

請幫忙!

邏輯:如果用戶輸入「左」(無論哪種情況,因爲我把它轉換爲小寫的任何方式)。它應該發送用戶到「deathPre(); 如果他輸入」正確「應該去「TrFight(); 任何事情都會導致一個我不介意的錯誤。但我需要的「左」和「右」的工作

+7

字符串比較需要使用.equals()完成,而不是== – 2013-04-11 19:30:59

回答

1

像以星 - 贊已經評論,您需要使用equals比較字符串,而不是==操作:

if(choice.toLowerCase().equals("right")) 
... 
else if(choice.toLowerCase().equals("left")) 

.toLowerCase()很可能就其工作很好。

4

確保你比較.equals()字符串,你也可以使用

.equalsIgnoreCase("left") 

如果使用第二個你不需要使用「.toLowerCase()」

編輯:

像Erik說的你也可以用

.trim().equalsIgnoreCase("left") 
+1

我還會使用'.trim()'刪除字符串開頭和結尾的空格。 – Erik 2013-04-11 19:36:51

1

你需要試試這個:

public static void part1() 
    { 
     System.out.println("Welcome to Chapter ONE "); 
     System.out.println("This is just a simple Left Right options."); 
     System.out.println("-------------------------"); 
     System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area."); 
     choice = input.next(); 
     if(choice.toLowerCase().equals("left")) 
     { 
      deathPre(); 
     } 
     else if(choice.toLowerCase().equals("right")) 
      { 
       TrFight(); 
      } 

比較兩個字符串,請使用String對象的equals方法。

相關問題