Java 字符串比较不是';工作不正常吗?
所以我尝试让用户输入一个字符串,向后打印,然后比较新字符串,看它是否是回文。。。它似乎不起作用,我不知道为什么Java 字符串比较不是';工作不正常吗?,java,string,compare,reverse,Java,String,Compare,Reverse,所以我尝试让用户输入一个字符串,向后打印,然后比较新字符串,看它是否是回文。。。它似乎不起作用,我不知道为什么 public static void main(String[] args) { Scanner input = new Scanner (System.in); System.out.print("Enter a word: "); String word = input.next(); StringBuilder drow = new StringB
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter a word: ");
String word = input.next();
StringBuilder drow = new StringBuilder(word);
drow.reverse();
System.out.println(drow);
System.out.print(" ");
String X = drow.toString();
if (word == X) {
System.out.println("That word is a palindrome");
} else {
System.out.println("That word is not a palindrome");
}
感谢您提供的任何帮助,解释为什么这不起作用…word==X询问它们是否是字面上相同的字符串(即,它们是指向内存中相同对象的两个引用),而不是它们是否相同(即,两个不同的字符串恰好包含相同的字母),您希望
string.equals(otherString)
我用这个比喻是同卵双胞胎。有两对同卵双胞胎询问他们是否是同一个人。equals()询问它们是否与您的比较引用看起来相同(使用==)。。使用equalsTo方法比较字符串内容。不要使用
==
。改用.equals()
:
if (word.equals(X)) {
System.out.println("That word is a palindrome");
}