验证字符串是否为回文数

时间:2022-11-04 09:57:38

一、程序设计思想:

通过将字符串转化为字符存放在字符数组中,然后再用递归依次比较字符的前后两个值是否相等,这样就判断出输入字符串是否为回文。

二、程序流程图:

验证字符串是否为回文数

 

 

三、源程序:

package homework2;

 

import java.util.Scanner;

 

publicclass Palindrome {

 

         staticchar []s1=newchar[100];

         publicstaticvoid main(String[] args) {

                   // TODO Auto-generated method stub

                  

                   System.out.println("输入你想测试的字符串:");

                   Scanner in=new Scanner(System.in);

                   int i=0;

                   String s=in.next();

                   s1=s.toCharArray();

                   if(judge(0)==1) {

                            System.out.println(s+"是回文。");

                   }

                   else {

                            System.out.println(s+"不是回文。");

                   }

 

 

         }

         publicstaticint judge(int n) {

                   if(s1[n]==s1[s1.length-1]) {

                            return  judge(n+1);

                   }

                   if(n>=s1.length/2) {

                            return 1;

                   }

                   else {

                            return 0;

                   }

      }

 

}

 

四、实现结果截图:

 验证字符串是否为回文数

 

(中文)

 验证字符串是否为回文数

 

(英文)