我正在练习制作自己的字符串反转工具。最重要的是,我在一个简单的应用程序中使用了该方法。但是..
当我在 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;
}
}