为什么我的程序没有识别if语句中两个字符串之间的比较?

时间:2013-12-15 23:01:05

标签: java if-statement

这是我的代码(下面列出的问题):     import java.util.Scanner;

公共类ExampleCode {

/**
 * B. Stephens
 */
public static void main(String[] args) {

    Scanner input = new Scanner (System.in);

    String secretPhrase = "show me the money";
    boolean notDone = true;

    while (notDone = true){
        System.out.print("Guess the puzzle: ");
        String puzzleGuess = input.nextLine();
        if (puzzleGuess == secretPhrase) {
            System.out.println("Congratulations! You guessed the puzzle!");
            notDone = false;
        }
    }

} // end main

出于某种原因,程序无法识别我的输入(puzzleGuess)何时与secretPhrase相同。似乎没有理由正确的输入不应该结束该程序。谢谢你的帮助!

5 个答案:

答案 0 :(得分:1)

使用.equals()而不是== 所以,你的if语句应该是这样的: if(puzzleGuess.equals(secretPhrase))

因为String被认为是一个对象,所以必须执行任何对象比较 使用.equals(Object o)。

希望我的回答有所帮助:)

答案 1 :(得分:0)

因为您需要使用.equals方法

if (puzzleGuess.equals(secretPhrase)) {
    System.out.println("Congratulations! You guessed the puzzle!");
    notDone = false;
}

Java字符串被实习,因此==有时可以工作。

public class InternedDemo {

    public static void main(String[] args) {
        String s1 = "hello world";
        String s2 = "hello world";
        String s3 = new String("hello world");

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // false
        System.out.println(s2 == s3); // false

       System.out.println(s1.equals(s3)); // true
       System.out.println(s2.equals(s3)); // true
   }
}

答案 2 :(得分:0)

请勿使用==比较字符串。使用secretPhrase.equals(puzzleGuess)==只是检查两个字符串是否都是同一个对象。

答案 3 :(得分:0)

使用.equals()与字符串

进行比较
public static void main(String[] args) {

Scanner input = new Scanner (System.in);

String secretPhrase = "show me the money";
boolean notDone = true;

while (notDone){
    System.out.print("Guess the puzzle: ");
    String puzzleGuess = input.nextLine();
    if (puzzleGuess.equals(secretPhrase)) {
        System.out.println("Congratulations! You guessed the puzzle!");
    secretPhrase=null;
        notDone = false;
    }
   }
}

答案 4 :(得分:0)

==不能用于比较字符串。对于非基元,==确定它们是否是同一个对象。要查看两个字符串是否具有相同的值,请使用.equals():

String str1 = new String("foo");
String str2 = str1;
String str3 = new String("foo");
String str4 = new String("bar");
System.out.println(str3 == str3); //true
System.out.println(str1 == str2); //true
System.out.println(str1 == str3); //FALSE!
System.out.println(str1.equals(str3)); //true!
System.out.println(str1 == str4); //false
System.out.println(str1.equals(str4)); //false