1

我正在练习字符串回文。我的 for 循环中的代码对吗?

public static void main (String args[]) 
{
    String word = JOptionPane.showInputDialog("Input a String:");
    String finalword = word.replaceAll(" ","").toLowerCase();

    for (int x = word.length(); x >= word.length()-1; x--) 
    {
        finalword.charAt(x);
    }

    if(word.equals(finalword)) 
    {
        JOptionPane.showMessageDialog(null, "Palindrome");
    }
    else 
    {
        JOptionPane.showMessageDialog(null, "Not a Palindrome");
    }
}    

感谢你并致以真诚的问候。

4

3 回答 3

2

当您启动 x 时,该值将是单词的长度。它应该是

int x = word.length() -1

于 2012-12-18T00:20:46.917 回答
2
  1. 您需要处理的实际字符串是 finalword,因为它的长度对您很重要。

  2. 为简单起见,取两个临时数组,如 tempStart 和 tempLast,两者的长度必须与 (finalword.length /2) 相同,不要担心字符串有偶数或奇数个字符。

  3. 使用带有两个变量的 for 循环,如下所示。

     for(int x = 0, y=finalword.length(); x<finalword.length() / 2; x++,y--){
       // check tempStart and tempLast has same chars.
       // I hope you know rule for palindrome.
     }
    
  4. 如果这两个数组(tempStart 和 tempLast)匹配,则它的回文不匹配。

我希望这能帮到您。如果不让我知道您在执行此操作时需要更多帮助。

于 2012-12-18T01:17:09.060 回答
0

int x = word.length(); 会给你字符数组的长度,即

"Racecar".length();
// 7

然后在数组中是数组 [7],但你真的想要 6

于 2012-12-18T00:21:14.343 回答