Java 软件测试编程题

1、计算给定字符串大小写字母出现次数,并打印。

public static void main(String[] args) {
        String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        
        int[] count = new int[52]; //用来存储字母a-z A-Z出现的次数。
         
        for(int i=0; i=65 && tmp<=90) {
                int index = tmp - 65;
                count[index] = count[index] +1;
            }else if(tmp>=97&& tmp<=122) {
                int index = tmp - 65+(7-1);
                count[index] = count[index] +1;
            }
        }
        
        //循环打印每个字母出现次数
        for(int j=0; j=65 && tmp<=90) {
                    System.out.println("字母"+(char)(j+65)+"出现次数:"+count[j]);}
                else if(tmp>=97&& tmp<=122) {
                    System.out.println("字母"+(char)(j+65+(7-1))+"出现次数:"+count[j]);  // 7是 ascii表大小写字母中间的其他字符
                }
            }
        }
    }

2、利用map 实现统计给定字符串中大小写字母及数字出现次数。

String str = "ADHfggegJKEFdjiwDdgrgrgfGgrgrRd123";
			//用map实现
			TreeMap map = new TreeMap();
			for(Character ch: str.toCharArray()){
				
				//判断是否为字母,其他符号不考虑统计
				if( (ch>='a' && ch<='z') || (ch>='A'&&ch<='Z')){
					Integer count = map.get(ch);
					map.put(ch, null==count?1:count+1);
				}else if(ch >= '0' && ch <= '9') {
					Integer count = map.get(ch);
					map.put(ch, null==count?1:count+1);
				}
			}
			//遍历map
			for(Map.Entry enter: map.entrySet()){
				
				System.out.println("字母:"+enter.getKey() +"出现次数:"+enter.getValue());
				
			}

遍历map 的其他方法:

(1)利用迭代器和KeySet集合

		 Set keySet = map.keySet();
		        //遍历存放所有key的Set集合
		        Iterator it =keySet.iterator();    
		        while(it.hasNext()){                         //利用了Iterator迭代器**
		            //得到每一个key
		        	Character key = it.next();
		            //通过key获取对应的value
		        	Integer value = map.get(key);
		            System.out.println(key+"="+value);
		        }
			

(2)利用迭代器和map的entrySet集合

			Iterator> iter = map.entrySet().iterator();
			 
			Map.Entry entry;
			 
			while (iter.hasNext()) {
			 
			    entry = iter.next();
			 
			    Character key = entry.getKey();
			 
			    Integer value = entry.getValue();
			    System.out.println("key = "+ key + ",vlaue = "+ value);
			 
			}

总结:for-each 效率较高,推荐使用。

 

3、比较两个数组的元素是否相等

使用数组的containsAll()方法


		//新建2个list,用来存储元素		
		List A = Arrays.asList("Tom","Anthony","Beijing");
		List B = Arrays.asList("Tom","Anthony","Beijing");
		
		if(A.containsAll(B)){
			System.out.println("相同");
		}else
			System.out.println("不相同");

这里补充说明下,定义不同类型的List 的格式:

注意:集合中只能存储引用数据类型,存储基本类型时,存储的类型为对应每个基本类型对应的引用数据。

int              Integer

double      Double

char          Character

String      String

List<Integer> inter= new ArrayList();
List<Character> char1= new ArrayList();
List<Double> dou= new ArrayList();

 

----------------------------

边联系边记录

 

 

 

 

 

你可能感兴趣的:(Java)