2
public static void main(String[] args) {
    String input = new String(JOptionPane.showInputDialog("Enter a string."));
    String inputLow = input.toLowerCase();

    String output = "";     //Blank string
    for(int i = 0; i < inputLow.length(); i++)  //For loop to continue through the entered string
    {
        if(inputLow.charAt(i) >= 'a' && inputLow.charAt(i) <= 'z')  //If statement to check for appropriate characters only
        {
            output += inputLow.charAt(i);   //Add only the appropriate characters to String output ('a' - 'z')
        }
    }
    System.out.println(output);

    //GETTING REVERSE STRING
    int n = output.length() - 1;
    String last = "";
    for(int k = n; k >= 0; k--)
    {
        System.out.print(output.charAt(k));
        //last = String.valueOf(output.charAt(k));
    }
    //System.out.println("");
//System.out.println(last);
}

所以我试图最后打印字符串,但是当我取消注释它输出的代码时:

heyman
namyeh
h

但我希望它在第三行打印“heyman”。(我只是在执行打印语句来测试它是否正确执行,我的目标是将 String last 与 String 输出进行比较,如果它们相同,则它是回文,否则不是。)

我怎么能用这种方法(或几乎类似的方法)来做到这一点?

4

1 回答 1

1

您一次将 last 的值设置为一个字符。您基本上每次都在重置它,这就是为什么它以反转字符串的最后一个字符(即第一个字符)结束的原因。

将其更改为last = String.valueOf(output.charAt(k)) + last;

于 2014-04-14T15:51:03.247 回答