package cn.wang.day10;
/**
* @author WangShiwu 1.分析以下需求,并用代码实现:
* (1)定义数字字符串数组{"010","3223","666","7890987","123123"}
* (2)判断该数字字符串数组中的数字字符串是否是对称(第一个数字和最后一个数字相等,第二个数字和倒数第二个数字是相等的,依次类推)的,并逐个输出
* (3)如:010 是对称的,3223 是对称的,123123 不是对称的 (4)最终打印该数组中对称字符串的个数
*
* 提示:循环获取字符串的每一个字符,依次比较第一个和最后一个,第二个和倒数第二个。。。
*/
public class Demo01_HomeWork {
public static void main(String[] args) {
/*String[] str = { "010", "3223", "666", "12211","12321", "7890987", "123123" };
int count = 0;
for (int index = 0; index < str.length; index++) {
int a = 0;
boolean sign = true;
for (int i = 0, j = str[index].length() - 1; i < j; i++, j--) {
if (str[index].charAt(i) != str[index].charAt(j)) {
a = 0;
sign = false;
break;
}
a = 1;
}
if(sign == true) {
System.out.println(str[index] + " 对称");
}
count = a + count;
}
System.out.println("数组中对称字符串的个数为:" + count);
}*/
//法2
String[] str = { "010", "3223", "666", "12211","12321", "7890987", "123123" };
int count = 0;
for(int index = 0 ; index < str.length; index++) {
if(fun(str[index])) {
count ++;
System.out.println(str[index]);
}
}
System.out.println("数组中对称字符串的个数为:" + count);
}
// 定义一个方法,然后判断某一个字符串是否是对称的
public static boolean fun(String str) {
for(int i = 0, j = str.length()-1; i < j; i++ ,j--) {
if(str.charAt(i) != str.charAt(j)) {
return false;
}
}
return true;
}
}
String的练习,收益多多,不同的方法,不同的世界
最新推荐文章于 2024-09-16 21:37:07 发布