2

我正在练习制作自己的字符串反转工具。最重要的是,我在一个简单的应用程序中使用了该方法。但是..
当我在 Eclipse 中运行我的代码时,即使 word 是 = racecar 并且 reversed 变成 = racecar(word reversed)。显示 else .. 告诉我 word 和 reverse 永远不相等.. 但是..ion 是这样的吗?正确的?请给我一些建议,这很糟糕。谢谢你。

import java.util.Scanner;

public class Main {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){

    System.out.println("Please enter a word, I'll show it reversed ");
    System.out.println("and tell you if it is read the same forward and backward(A Palindrome)!: ");
        String word = sc.nextLine();
        String reverse = reverse(word);

        if (reverse == word){
            System.out.println("Your word: " + word + " backwards is " + reverse + ".");
            System.out.println("Your word is read the same forward and backward!");
            System.out.println("Its a Palindrome!");
        }

        else {
            System.out.println("Your word: " + word + " backwards is " + reverse + ".");
            System.out.println("Your word is not read the same forward and backward!");
            System.out.println("Its not a Palindrome!");
        }



    }

    public static String reverse(String source){

        if (source == null || source.isEmpty()){
            return source;
        }

        String reverse = "";

        for(int i = source.length() -1; i >= 0; i--){
            reverse = reverse + source.charAt(i);
        }

        return reverse;
    }

}
4

4 回答 4

10

始终使用String#equals来比较字符串。==将比较引用是否相等,由于它们的存储方式,这实际上不适用于比较相等的字符串。

if (reverse.equals(word))
于 2013-07-24T01:56:17.990 回答
3

为什么你没有出现 if 的原因是因为你不能使用 == 来表示字符串。您只能在 math/int/double/float 等比较中做到这一点

对于字符串比较,您必须使用

 equals(String s) 

或对于不必完全相同的单词大写

 equalsIgnoreCase(String s)
于 2013-07-24T01:56:57.913 回答
3

你应该使用equals方法比较两个字符串,字符串是一个对象,这是一个引用,equals()方法会比较两个字符串的内容,但是==会比较两个字符串的地址

所以,你应该这样写:

if (reverse.equals(word))
于 2013-07-24T07:15:18.923 回答
1

在 Java 中,对象(包括字符串)作为引用存储——它们在内存中的位置。

操作员检查这些==引用是否相等,而不是实际字符串是否相等。

幸运的是,Java 有一个解决方法。如果两个字符串具有相同的内容,则String 方法equals(String)将返回 true。将此用于字符串,而不是==.

于 2013-07-24T01:59:48.710 回答