0

这就是我必须解决的问题。我需要保留已经写好的内容,但我不知道如何使用循环和 charAt() 来查找回文。输入的是在终端行中写入字符串所需的代码,因此我无法输入任何内容。有什么建议么?

import java.io.*;
import java.util.*;


public class Palindrome
{
public static void main (String[] args) throws IOException
{
    try // WE WILL TALK ABOUT EXCEPTIONS EVENTUALLY - JUST PUT ALL YOUR CODE IN THIS TRY BLOCK
    {


        // --------------------------------------------------------------------------------------------------------


        if (args.length == 0) 
        {
            System.out.println("FATAL ERROR: Must enter a word on the command line!\n");
            System.exit(0);
        }


        String word = args[0];  


        boolean isPalindrome=true;  


        // --------------------------------------------------------------------------------------------------------







        // --------------------------------------------------------------------------------------------------------

        if (isPalindrome)
            System.out.println( word + " IS a palindrome." );
        else
            System.out.println( word + " NOT a palindrome." );

    }
    catch ( Exception e ) 
    {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        System.out.println("EXCEPTION CAUGHT: " + sw.toString() );
        System.exit( 0 );
    }
} // END main


} //END CLASS Palindrome
4

2 回答 2

1

总而言之 ,请i in 0..n/2确保这word[i] == word[someIndexThatDependsOnI]真的。(也就是说,如果any word[i] == word[someIndexThatDependsOnI]false则不是回文。使用适当的关键字可以在此时停止循环。)

我将发现留给someIndexThatDependsOnI读者,但它涉及到字符串的大小..

于 2012-09-20T22:13:50.123 回答
0
public bool isPalindrom(String word) {
  for (int i = 0;i < word.length/2; i++) {
     if (word.charAt(i) != word.charat(word.length - i - 1)) {
      return false;
     }
  }
   return true;
}

不过,您必须检查编程错误,因为我现在没有 IDE

干杯

于 2012-09-20T22:16:33.023 回答