2013-04-11 47 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方法。

相关问题