2012-08-27 47 views
0

嗨我有一些代码让Java控制台在按下特定键时执行某些操作。系统输入并存储密钥作为字符串没有麻烦,我可以打印出来确认它的工作原理。但是,代码永远不会进入条件语句,而是每次都跳转到else。这里是代码:当输入特定键时输入循环 - Java

Scanner MenuChoice = new Scanner(System.in); 
    Products.MenuCode = MenuChoice.next(); 


       if(Products.MenuCode=="F") 
       { 
       //Run subprogram for finding a product. 
       Find.main();  

       } 

       else{ 
       System.out.println("F - Find a Product"); 
       System.out.println("p - Purchase a Product"); 
        System.out.println("Q - Quit"); 
        Scanner MenuChoice2 = new Scanner(System.in); 
        Products.MenuCode = MenuChoice2.next(); 
       }; 

怎么回事?

回答

3

你可以做到这一点

Scanner MenuChoice = new Scanner(System.in); 
Products.MenuCode = MenuChoice.next(); 


      if(Products.MenuCode.equals("F")) // use equals method 
      { 
      //Run subprogram for finding a product. 
      Find.main();  

      } 

      else{ 
      System.out.println("F - Find a Product"); 
      System.out.println("p - Purchase a Product"); 
       System.out.println("Q - Quit"); 
       Scanner MenuChoice2 = new Scanner(System.in); 
       Products.MenuCode = MenuChoice2.next(); 
      }; 
+0

感谢那些解决它:) – user1627774

+0

,如果你得到你的答案,那么你可以接受的答案一样http://meta.stackexchange.com/questions/5234/how -does接受-的回答工作 –

0

你不能比较使用字符串==你必须使用等于梅索德。

equals方法是这样的:

boolean b = string1.equals(string2);