分析以下需求,并用代码实现:
(1)定义数字字符串数组{“010”,“3223”,“666”,“7890987”,“123123”}
(2)判断该数字字符串数组中的数字字符串是否是对称(第一个数字和最后一个数字相等,第二个数字和倒数第二个数字是相等的,依次类推)的,并逐个输出
(3)如:010 是对称的,3223 是对称的,123123 不是对称的
(4)最终打印该数组中对称字符串的个数
代码:
public class Demo06 {
public static void main(String[] args) {
//定义数字字符串数组
String[] str = {"010","3223","666","7890987","123123"};
String[][]str1;
print(str);
}
/*
* 打印字符串并输出对称个数
*/
public static void print(String[] str) {
//统计对称的个数
int count = 0;
//循环取出每一个字符串
for (int i = 0; i < str.length; i++) {
//调用isSymmetric()方法判断每一个字符串是否对称,对称,count加1
if(isSymmetric(str[i])) {
System.out.println(str[i]+"是对称的");
count++;
}else {
System.out.println(str[i]+"不是对称的");
}
}
System.out.println("该数字字符串数组中对称字符串的个数为"+count);
}
/*
* 判断字符串是否对称
*/
public static boolean isSymmetric(String str) {
//将字符串转换为字符数组
char[] ch = str.toCharArray();
//循环数组,依次比较第一个,最后一个;第二个,最后第二个....
for (int min = 0,max = ch.length - 1; min <= max;min++,max--) {
if(ch[min] != ch[max]) {
return false;
}
}
//执行到这里说明,没有执行if,字符串对称,返回true
return true;
}
}