第13周作业集
题目1:创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。
import java.util.*; public class jj { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> s=new ArrayList<String>(); s.add("chen"); s.add("wang"); s.add("liu"); s.add("zhang"); ArrayList<String> s1=new ArrayList<String>(); s1.add("chen"); s1.add("hu"); s1.add("zhang"); ArrayList<String> J=new ArrayList<String>(); J.addAll(s); J.retainAll(s1); System.out.println("交集为:"+J); HashSet<String> B=new HashSet<String>(); B.addAll(s); B.addAll(s1); System.out.println("并集为:"+B); } }
题目2:编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Test { public static void main(String[] args) { System.out.println("请输入一个字符串:"); HashMap<String, String> M = new HashMap<String, String>(); //创建散列映射 Scanner reader = new Scanner(System.in); String str = reader.nextLine(); String c; int length = str.length(); int num = 0; int A = 0; int a = 0; for(int i = 0 ; i < length ; i++){ c = str.substring(i, i+1); if(c.matches("\\d")){//判断是否为数字; if(M.get("数字")==null){ M.put("数字", c); } else{ M.put("数字", M.get("数字")+","+c); } num++; } if(c.matches("[a-z]")){//判断是否为小写字母; if(M.get("小写字母")==null){ M.put("小写字母", c); } else{ M.put("小写字母", M.get("小写字母")+","+c); } a++; } if(c.matches("[A-Z]")){//判断是否为大写字母; if(M.get("大写字母")==null){ M.put("大写字母", c); } else{ M.put("大写字母", M.get("大写字母")+","+c); } A++; } } Set set = M.entrySet(); //返回包含映射中项的集合; Iterator it = set.iterator(); //获取迭代对象; while(it.hasNext()){ Map.Entry me = (Map.Entry)it.next(); System.out.print(me.getKey()); if(me.getKey().equals("数字")){ System.out.print("——共有"+num+"个,"); }else if(me.getKey().equals("小写字母")){ System.out.print("——共有"+a+"个,"); }else if(me.getKey().equals("大写字母")){ System.out.print("——共有"+A+"个,"); } System.out.println("分别为:"+me.getValue()); } } }