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);
}
所以我最后一次尝试打印String,但当我取消注释该代码时,它会输出:
heyman
namyeh
h
但我希望它在第三行打印“heyman”。 (我只是在执行print语句来测试它是否正确执行,我的目标是将String last与String输出进行比较,如果它们是相同的则它是Palindrome,否则它不是。)
如何使用特定的方法(或类似的方法)来做到这一点?
答案 0 :(得分:1)
您一次将最后一个值设置为一个字符。你基本上每次都重置它,这就是为什么它以反向字符串的最后一个字符结束(这是第一个字符)。
将其更改为last = String.valueOf(output.charAt(k)) + last;