我正在练习制作自己的字符串反转工具。
最重要的是我在一个简单的应用程序中使用了该方法的学习过程。
但..结果
当我在Eclipse中运行我的代码时,
即使单词是=赛车
并逆转成=赛车(反转)。
其他显示..
告诉我这个词和相反是不相等的..但.. ..他们是这样的情况?对?
请给我一些建议,这是非常糟糕的。
谢谢。
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;
}
}