如何向后打印单词

时间:2014-11-13 22:31:07

标签: java string palindrome

所以我正在检查单词输入以查看它是否是回文。我的代码中的错误似乎与两个字符串的比较有关。我使用.equals()来测试相等的值,但它不起作用。 有什么想法吗?

这是我的代码:

public class PalindromeTask08 
{

public static void main(String[] args) 
{
    Scanner in = new Scanner (System.in);
    int count = 5;
    int x =0;

    //loops to input a word 
    do{
        System.out.println("input a word");
        String answer = in.next();
        char[] wordBackwards=new char[answer.length()];


        System.out.printf("The lenght of the word inputted is: %s%n", answer.length());

        for(int i= answer.length() ; i>0 ; --i)
        {

            wordBackwards[x] = answer.charAt(i-1);
            x++;
        }

        x=0;

        wordBackwards.toString();
        System.out.println(wordBackwards);

        if (answer.equals(wordBackwards))
        {
            System.out.printf("%s is a palindrome", answer);
            --count;
            System.out.printf("you have %d more attempts", count);
        }
        else
        {
            System.out.printf("%s is NOT a palindrome", answer);
            --count;
            System.out.printf("you have %d more attempts", count);

        }

    }while(count!=0);
    in.close();



    }

}

1 个答案:

答案 0 :(得分:1)

你的问题是

wordBackwards.toString();

它没有做任何让你返回数组地址的东西。
你需要像这样替换它才能使它工作:

...
x=0;
String backWordsString = new String(wordBackwards);
System.out.println(backWordsString);
if (answer.equals(backWordsString)) {
...

更简单的方法是

public class PalindromeTask08 {
    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        int count = 5;
        int x =0;

        //loops to input a word 
        do {
            System.out.println("input a word");
            String answer = in.next();
            if (answer.equals(new StringBuilder(answer).reverse().toString())) {
                System.out.printf("%s is a palindrome", answer);
            } else {
                System.out.printf("%s is NOT a palindrome", answer);
            }
            --count;
            System.out.println("\n you have %d more attempts "+ count);
        } while(count!=0);
        in.close();
    }
}

详细了解StringBuilder

相关问题