题目1:创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。
//通过retainAll方法获得交集 hashset去除重复的元素 import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class Text { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> str1=new ArrayList<String>(); ArrayList<String> str2=new ArrayList<String>(); ArrayList<String> j=new ArrayList<String>(); ArrayList<String> b=new ArrayList<String>(); List list = Arrays.asList("chen","wang","liu","zhang"); str1.addAll(list); List list1 = Arrays.asList("chen","hu","zhang"); str2.addAll(list1); j.addAll(str1); j.retainAll(str2); System.out.println("线性表的交集"+j.toString()); b.addAll(str1); b.addAll(str2); Set set=new HashSet<String>(); set.addAll(b); System.out.println("并集是"+set); } }
运行界面
题目2:编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。
package com; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; import java.util.Set; import java.util.Map; public class Map1 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入一个字符串"); Scanner reader = new Scanner(System.in); String str = reader.nextLine(); String num = "\d"; String min= "[a-z]"; String max = "[A-Z]"; HashMap<String, String> hm = new HashMap<String, String>(); int num1=0,num2=0,num3=0; for(int i=0;i<str.length();i++){ String character = str.substring(i, i+1); if(character.matches(num)){ if(hm.get("数字")==null){ hm.put("数字", character); }else{ hm.put("数字", hm.get("数字")+","+character); } num1++; } if(character.matches(min)){ if(hm.get("小写")==null){ hm.put("小写", character); }else{ hm.put("小写", hm.get("小写")+","+character); } num2++; } if(character.matches(max)){ if(hm.get("大写")==null){ hm.put("大写", character); }else{ hm.put("大写", hm.get("大写")+","+character); } num3++; } } Set set = hm.entrySet(); Iterator it = set.iterator(); while(it.hasNext()){ Map.Entry m = (Map.Entry)it.next(); System.out.print(m.getKey()); if(m.getKey().equals("数字")){ System.out.print(+num1); }else if(m.getKey().equals("小写")){ System.out.print(+num2); }else if(m.getKey().equals("大写")){ System.out.print(+num3); } System.out.println(" "+m.getValue()); } } }
运行界面