第三次课,课上测试

package three;
import java.util.Scanner;
   
    public class Huiwen {
        public static void main(String[]args){
        System.out.println("请输入需要判断字符串:");
        Scanner in = new Scanner(System.in);
        String str=in.next();
        int n=str.length();
        int m=huiwen(str,n);
        if(m==1)
        System.out.println("yes");
        else
        System.out.println("NO");
        }
    public static int huiwen(String str,int n){
        int a,b,j=0;
        char c1,c2;
        a=str.length()-n; //正移
        
        b=str.length()-(a+1);  //倒移
        
        c1=str.charAt(a);  //取字符
        c2=str.charAt(b);  //取字符
        
        if(c1==c2||a==b) j=1;  //递归
        
        if(a != b && a<b && j==1 )
        huiwen(str,n-1);
        return j;
        }
    }

代码如上,输入字符串会自动进行判断其是否为回文字符串。

运行结果如下:

 设定一个函数用递归的方式判断其是否为回文字符串,主函数则先判断字符串长度,长度为一时,输出为回文字符串。

长度不为一时,调用函数进行判断和输出。

原文地址:https://www.cnblogs.com/520520520zl/p/11579607.html