Java不是说两个字符串相等吗?

时间:2011-09-14 02:27:52

标签: java string equality

  

可能重复:
  String comparison in Java

继承我的剧本:

public class euler4 {

    /**
     * a palindromatic number reads the same both ways. the largest palindrome
     * made from the product of 2-digit numbers is 9009 = 91 * 99.
     * 
     * find the largest palindrome made from the product of two 3-digit numbers.
     */
    public static void main(String[] args) {
        /*for(int t = 100; t < 200; t++) {
            for(int l = 100; l < 100; l++) {
                String milah = "" + t * l;
                String result = palin(milah);
                if(result != "no_pali") {
                    System.out.println(milah);
                }
            }
        } */
        String result = palin("abba");
        System.out.println(result);
    }

    public static String palin(String the_num) {
        int orech = the_num.length();
        String back_word = "";
        /**
         * the for loop has the counter starting at the orech of the number, then
         * decrementing till 0 (or the 0'th index)
         */
        for(int i = orech - 1; i >= 0; i--) {
            back_word = back_word + the_num.charAt(i);
        }
        System.out.println(the_num);
        System.out.println(back_word);
        System.out.println(back_word == "abba");
        if(back_word == the_num) {
            return back_word;
        } else {
            return "no_pali";
        }

    }
}

在第34行打印“abba”就像它应该

在第35行,它打印出“abba”的精确副本,就像它应该

它在第36行变得奇怪,这是:

System.out.println(back_word == "abba");

并打印错误..... ??

它打印了这些单词的精确副本,但是当我比较它们时,它会给出错误的结果!?

因为他们不相等(当他们真的这么做时)它返回了错误的东西

6 个答案:

答案 0 :(得分:19)

在java中,==运算符比较对象的地址。

要比较两个字符串是否相等,您需要使用.equals()函数。

back_word.equals("abba");

答案 1 :(得分:4)

改为使用back_word.equals("abba");

Java中的

==测试它们是同一个对象,因此back_word == back_word会返回true

然后,String Class的.equals方法检查

  

如果给定对象表示与此字符串等效的String,否则为

取自:String's Javadoc

答案 2 :(得分:3)

您需要使用String.equals()而不是比较指针。

back_word.equals("abba");

(如果适用,请参阅String.equalsIgnoreCase()

答案 3 :(得分:3)

因为==比较它们是内存中的同一个对象,它们不是。它们代表相同的数据,但它们不是同一个对象。

您需要back_word.equals("abba")

答案 4 :(得分:3)

Java中的==运算符执行对象相等而不是值相等。 back_word和“abba”是两个不同的对象,但它们可能具有相同的值。

您正在寻找的是等于方法:

System.out.println(back_word.equals("abba"));

答案 5 :(得分:1)

在String类型的上下文中,使用==按引用进行比较(内存位置)。

除非你将字符串与其确切的self进行比较,否则它将返回false。

尝试使用方法equals(),因为它按值进行比较,你应该得到你需要的东西。