Я пишу программу, которая определяет, является ли слово/фраза до 8 символов палиндром. Независимо от того, что я вставляю в качестве ввода, даже если это палиндром, моя программа печатает мое заявление else. Я проверил и убедился, что код, который я написал, фактически печатает вход в обратном порядке, и это происходит. Поэтому я не совсем уверен, в чем проблема.Почему моя инструкция if не работает правильно?
import java.util.Scanner;
public class hw5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word, newWord;
int lengthOfWord;
char lc;//last character
System.out.print("Enter word/phrase of 8 characters or less: ");
word = in.nextLine();
word = word.toLowerCase();
newWord = word;
lengthOfWord = word.length();
lc = word.charAt(lengthOfWord -1);
lc = word.charAt(lengthOfWord -1);
if (word.length() == 2)
newWord = lc+word.substring(0,1);
else if (word.length() == 3)
newWord = lc+word.substring(1,2)+word.substring(0,1);
else if (word.length() == 4)
newWord = lc+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
else if (word.length() == 5)
newWord = lc+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
else if (word.length() == 6)
newWord = lc+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
else if (word.length() == 7)
newWord = lc+word.substring(5,6)+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
else if (word.length() == 8)
newWord = lc+word.substring(6,7)+word.substring(5,6)+word.substring(4,5)+word.substring(3,4)+word.substring(2,3)+word.substring(1,2)+word.substring(0,1);
else
newWord = "error, not enough or too many characters";
if (newWord == word)
System.out.println("it is a palindrome");
else
System.out.println("it is not a palindrome");
System.out.println(newWord);
Используйте метод 'stals'' equals' для сравнения строковых значений, а не '==' оператор, который определяет, ссылаются ли на две ссылки на один и тот же объект. – rgettman