我怎么能解决这个副作用?

时间:2013-01-10 17:14:09

标签: java loops statements

  

可能重复:
  How do I compare strings in Java?

我遇到以下代码的问题;问题是,在你第一次没有说地图之后,无论你输入的是“地图”,它都会在输入框中不断重复No try again

 System.out.println("My cousin Diego is in trouble in the Majestic palace. But how do we get there?");
 System.out.println("Who do we call when we don't know where to go?         Huh? I didn't get that...");
 imTheMap=robotMagic.next();
 if (imTheMap.equals("map"))
 {
    System.out.println("That's right!"); //the issue is here
 }
 else 
 {
    while(imTheMap!=("map"))
    {
        System.out.println("No! try again");
        imTheMap=robotMagic.next();
    }
 }

1 个答案:

答案 0 :(得分:6)

通过更改

 while(imTheMap!=("map"))

 while(!imTheMap.equals("map"))

总是应该使用equals()方法来检查字符串相等性。就像你的if语句一样。