第13周作业集
题目1:创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。
package factorial; import java.util.*; public class text { public static void main(String[] args) { ArrayList<String> test1 = new ArrayList<String>(4); ArrayList<String> test2 = new ArrayList<String>(3); test1.add("chen"); test1.add("wang"); test1.add("liu"); test1.add("zhang"); test2.add("chen"); test2.add("hu"); test2.add("zhang"); //交集 ArrayList<String> test3 = new ArrayList<String>(); for(int i = 0; i < test1.size(); i++) { for(int j = 0; j < test2.size(); j++) { if(test1.get(i).equals(test2.get(j))) { test3.add(test1.get(i)); test2.remove(j); } } } System.out.println("交集为:" +test3); //并集 ArrayList<String> test4 = new ArrayList<String>(); test4.addAll(test1); test4.addAll(test2); System.out.println("并集为:"+test4); } }
运行结果:
题目2:编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。
package sdds; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ddd { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入一行字符串:"); String str = sc.nextLine(); HashMap al=new HashMap(); HashMap bl=new HashMap(); HashMap cl=new HashMap(); char[] arr = str.toCharArray(); int a = 0;//大写字母 int b = 0;//小写字母 int c = 0;//数字 for (int i = 0; i < arr.length; i++) { char ch = arr[i]; if (ch >= 'A' && ch <= 'Z') { a++; al.put(i,arr[i]+","); continue; } if (ch >= 'a' && ch <= 'z') { b++; bl.put(i,arr[i]+","); continue; } if (ch >= '0' && ch <= '9') { c++; cl.put(i,arr[i]+","); continue; } } System.out.print("大写字母———共"+a+"个,"+"分别为"+""); Set set=al.entrySet(); Iterator tao=set.iterator(); while(tao.hasNext()){ Map.Entry y1=(Map.Entry)tao.next(); System.out.print(y1.getValue()); } System.out.println(""); System.out.print("小写字母———共"+b+"个,"+"分别为"+""); Set set1=bl.entrySet(); Iterator ming=set1.iterator(); while(ming.hasNext()){ Map.Entry y2=(Map.Entry)ming.next(); System.out.print(y2.getValue()); } System.out.println(""); System.out.print("数字———共"+c+"个,"+"分别为"+""); Set set2=cl.entrySet(); Iterator ming1=set2.iterator(); while(ming1.hasNext()){ Map.Entry y3=(Map.Entry)ming1.next(); System.out.print(y3.getValue()); } }}
运行结果: