2013-09-25 91 views
1

我正在编写一个程序,用于查找最多8个字符的单词/短语是否是回文。不管我输入什么东西,即使它是一个回文,我的程序都会打印我的其他语句。我检查并确保我写的代码实际上是反向输入并输入。所以我不太确定问题是什么。为什么我的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); 
+1

使用'String'的'equals'方法来比较两个字符串值,而不是''==操作符,它决定了两个引用是否指向同一个对象。 – rgettman

回答

2
if (newWord.equals(word)) 
     System.out.println("it is a palindrome"); 
else 
     System.out.println("it is not a palindrome"); 

当您使用==,言不相比较,有什么比较是在内存中的两个变量的指标。

2

==表示运行时将检查它们是否指向相同的地址,equals将检查两个对象是否具有相同的内容。因此,请尝试使用equals方法来比较字符串和==的数字。

4

你可以把它变得简单许多。

word = word.toLowerCase(); 
newWord = new StringBuilder(word).reverse().toString(); 

if (newWord.equals(word)) 
    System.out.println("it is a palindrome"); 
else 
     System.out.println("it is not a palindrome"); 
2

String s是对象。而字符串变量只是指向字符串对象的指针。所以,当你做if(newWord==word),你不比较字符串的内容,而你在比较这些指针的值(存储位置的指针指向太)。您需要使用Stringequals方法,以内容比较两个字符串。

相关问题