第13周作业集
题目1:创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。
注释:
创建一个类,类中生声明3个变量,并存入元素,求出交集并集。
jj.retainAll(b);//交集删除相同的
a.removeAll(b);//移除并集中重复
2.代码部分
package aa; import java.util.ArrayList; public class Test { /** 创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和 {“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。 */ public static void main(String[] args) { ArrayList<String> a=new ArrayList<String>(); ArrayList<String> b=new ArrayList<String>(); ArrayList<String> jj=new ArrayList<String>();//交集集合 System.out.println("请输入线性表a的内容"); a.add("chen"); a.add("wang"); a.add("liu"); a.add("zhang"); b.add("chen"); b.add("hu"); b.add("zhang"); System.out.println("集合一的内容"+a); System.out.println("集合二的内容"+b); jj.addAll(a); jj.retainAll(b);//交集删除相同的 System.out.println("交集线性表的内容"+jj); a.removeAll(b);//移除并集中重复 a.addAll(b); System.out.println("并集线性表的内容"+a); } }
2.测试运行
题目2:编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。
代码注释
用正则运算判断字符,用迭代获取整个串,输入一个字符串
判断是否为数字,大写字母或小写字母,并计算出个数,输出结果
代码部分
package aa; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; public class Test2 { private static int i; public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("输入一个字符串,该串至少由数字、大写字母和小写字母三种字符"); String str=input.nextLine(); String num = "\\d"; String xiao = "[a-z]"; String daxie = "[A-Z]";//正则判断格式 HashMap<String,String> hash=new HashMap<String,String>(); int count1=0,count2=0,count3=0; for(int i=0;i<str.length();i++){ String word = str.substring(i, i+1); if(word.matches(num)){ if(hash.get("数字")==null){ hash.put("数字", word); }else{ hash.put("数字", hash.get("数字")+","+word); } count1++; } if(word.matches(xiao)){//判小写字母 if(hash.get("小写字母")==null){ hash.put("小写字母", word); }else{ hash.put("小写字母", hash.get("小写字母")+","+word); } count2++; } if(word.matches(daxie)){ if(hash.get("大写字母")==null){ hash.put("大写字母", word); }else{ hash.put("大写字母", hash.get("大写字母")+","+word); } count3++; } } Set set = hash.entrySet();//返回包含映射中项的集合 Iterator dd= set.iterator();//用迭代器获取 while(dd.hasNext()){ Map.Entry map= (Map.Entry)dd.next(); System.out.print(map.getKey()); if(map.getKey().equals("数字")){ System.out.print("——共"+count1+"个,"); }else if(map.getKey().equals("小写字母")){ System.out.print("——共"+count2+"个,"); }else if(map.getKey().equals("大写字母")){ System.out.print("——共"+count3+"个,"); } System.out.println("分别是:"+map.getValue()); } } }
测试运行