无法获得if语句的工作

时间:2012-10-28 02:10:41

标签: java

  

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

import java.util.Scanner;

 public class stringComparer {
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        System.out.println ("Enter 1 word here - ");
        String word1 = scan.next();

    System.out.println ("Enter another word here - ");
    String word2 = scan.next();

    if (word1 == word2) {
        System.out.println("They are the same");
    }
}
}

我让它在大约10分钟前工作,改变了一些东西现在由于某种原因它没有显示“它们是相同的”?它真的很简单,但我看不出哪里出错了。

谢谢!

3 个答案:

答案 0 :(得分:1)

==运算符通过引用比较对象

要确定两个不同的String个实例是否保持相同的值,请致电.equals()

因此,请替换

if (word1 == word2)

if (word1.equals(word2))

答案 1 :(得分:0)

请尝试此操作,String is not primitive这样当您检查==时,它会检查参考文献。

import java.util.Scanner;
/**
 * This program compares two strings
 * @author Andrew Gault
 * @version 28.10.2012
 */
 public class stringComparer
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner (System.in);
        System.out.println ("Enter 1 word here - ");
        String word1 = scan.next();

    System.out.println ("Enter another word here - ");
    String word2 = scan.next();

    if (word1.equals(word2))
    {
        System.out.println("They are the same");
    }

}
}

答案 2 :(得分:0)

使用

if (word1.equals(word2))
{
 System.out.println("They are the same");   
}

了解原因here