Day_11【集合】扩展案例2_使用普通for循环获取集合中索引为3的元素并打印,统计集合中包含字符串"def"的数量,删除集合中的所有字符串",将集合中每个元素中的小写字母变成大写字母def",

分析以下需求,并用代码实现

  •  1.定义ArrayList集合,存入多个字符串"abc" "def"  "efg" "def" "def" "qwe" "def" "def" "swd" "wwe" "def" "def"
     2.使用普通for循环获取集合中索引为3的元素并打印
     3.定义方法public static boolean myContains(ArrayList list,String str)
     	(1)参数
     		a.ArrayList list: 表示存储多个String数据的集合
     		b.String str: 表示一个字符串
     	(2)返回值
     		true: 表示list集合中包含字符串str
     		false: 表示list集合中不包含字符串str
     4.利用上面定义的mycontains方法统计集合中包含字符串"def"的数量
     5.删除集合中的所有字符串"def"(思路:循环判断集合中是否包含"def"字符串,包含就删除)
     6.将集合中每个元素中的小写字母变成大写字母
    
import java.util.ArrayList;

public class Test2 {
	public static void main(String[] args) {
		// 创建集合对象
		ArrayList<String> array = new ArrayList<String>();

		// 添加元素到集合中
		array.add("abc");
		array.add("def");
		array.add("efg");
		array.add("def");
		array.add("def");
		array.add("qwe");
		array.add("def");
		array.add("def");
		array.add("swd");
		array.add("wwe");
		array.add("def");
		array.add("def");

		// 使用普通for循环获取集合中索引为3的元素并打印
		for (int x = 0; x < array.size(); x++) {
			String s = array.get(x);
			if (x == 3) {
				System.out.println(s);
			}
		}
		
		// 调用getDataCount()方法统计集合中包含字符串"def"的数量
		int count = getDataCount(array, "def");
		System.out.println("集合中字符串“def”的数量为:" + count);
		
		
		toUpperCaseForList(array);
		System.out.println(array);
		
		
	}
	//定义方法public static void toUpperCaseForList(ArrayList list)
	//将集合中每个元素中的小写字母变成大写字母
	/*
	 * 方法:public String toUpperCase()
	 * 作用:使用默认语言环境的规则将此 String 中的所有字符都转换为大写
	 */
	public static void toUpperCaseForList(ArrayList<String> list) {
		StringBuilder sb = new StringBuilder();
		for(int x = 0;x < list.size();x++) {
			String s = list.get(x);
			list.set(x, s.toUpperCase());
		}
	}
	
	
	
	//定义方法public static int getDataCount(ArrayList list,String str)
	//统计集合中包含字符串"def"的数量,删除集合中的所有字符串"def"
	public static int getDataCount(ArrayList<String> list,String str) {
		int count = 0;
		while(myContains(list, str)) {						
			list.remove(str);
			count++;
		}
		return count;
	}
	
	// 定义方法public static boolean myContains(ArrayList list,String str)
	/*
	 * 方法:public boolean contains(Object o)
	 * 作用:如果此列表中包含指定的元素,则返回 true
	 * 		更确切地讲,当且仅当此列表包含至少一个满足 (o==null ? e==null : o.equals(e)) 的元素 e 时,则返回 true
	 */
	public static boolean myContains(ArrayList<String> list, String str) {
		return list.contains(str);
	}

}

控制台输出内容
控制台输出内容

posted @ 2019-12-21 19:09  _codeRookie  阅读(313)  评论(0编辑  收藏  举报