分析以下需求,并用代码实现
1.定义ArrayList集合,存入多个字符串
如:"ab1" "123ad" "bca" "dadfadf" "dddaaa" "你好啊" "我来啦" "别跑啊"
2.遍历集合,删除长度大于5的字符串,打印删除后的集合对象
3.基于上一步,删除集合中元素包含0-9数字的字符串(只要字符串中包含0-9中的任意一个数字就需要删除此整个字符串)
解题:
import java.util.ArrayList;
public class HomeWork4 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
String[] arr = {"ab1","123ad","bca","dadfadf","dddaaa","你好啊","我来啦","别跑啊"};
for(int i = 0;i<arr.length;i++){
list.add(arr[i]);
}
for(int i = 0;i<list.size();i++){
if(list.get(i).length()>5){
list.remove(i);
//主要是这里,要让i自减1
i--;
}
}
System.out.println(list);
for(int i=0;i<list.size();i++){
if(isContains(list.get(i))){
list.remove(i);
//这里也是,要让i自减1
i--;
}
}
System.out.println(list);
}
private static boolean isContains(String string) {
char[] arr = string.toCharArray();
for(int i= 0 ;i<arr.length;i++){
if(arr[i]>='0'&&arr[i]<='9'){
return true;
}
}
return false;
}
}
|
|