Recursively determining whether the input character string is a palindrome

Design: introducing Scanner type of input string, then the string entered into an array of characters, and the left and right sides of the string of characters chu sequence comparison are the same, the same recursion return if the number of characters to read, if the characters returned the number == length of the input string, the string is a palindrome output, or the output of the string is not a palindrome

 

Import java.util.Scanner; 

public  class test1 { 

    public  static  void main (String [] args) {
         // the TODO Auto-Generated Method Stub 
        Scanner INPUT = new new Scanner (the System.in); 
        String A = input.nextLine ();
         char [] TEMP = a.toCharArray ();         
         int C = Fun (0,. 1-temp.length , TEMP);
         IF (C == temp.length) 
            System.out.println ( "the string is a palindrome " );
         the else 
            System.out.println ( " the string is not a palindrome "); 
        Input.close (); 
    } 

    public  static  int Fun ( int I, int J, char [] A) {    // definition of a function to determine whether the string is a palindrome 
        
        IF (J == I)      // string length odd 
            return . 1 ;
         the else  iF (I - J ==. 1)   // string length is even 
            return 0 ;
         the else {
             iF (a [I] == a [J])         // determined characters are the same on both sides of 
            { 
                I ++ ; 
                J -;
                 Return (2 + Fun (I, J, A));   // recursive call functions 
            }
             the else 
                return -100;   // if the characters on both sides do not directly call the end 
        } 
    } 
}

 

Experiences: the beginning because for recursion is not thorough enough understanding, the main condition for ending the recursion is not clear, always thought to add a break before they can end calls, and later came to realize that the recursive function refers to the end of the last call.

next and nextLine difference:

next () method at the time of reading the content, will effectively filter out invalid characters preceding character of the spacebar encountered before entering a valid character, Tab or Enter key, etc. terminator, next () method will automatically filter out ; read only after a valid character, next () method until the subsequent space key, Tab key or the Enter key, etc. considered terminator; so next () method of the string can not be obtained with spaces.

nextLine () method of scanning an entire row literally meaning, it is only the Enter key terminator, i.e. nextLine () method returns all the characters have not been read before the Enter key, it is possible to obtain with spaces string.

 

Guess you like

Origin www.cnblogs.com/weixiao1717/p/11586586.html