1. 程式人生 > >ArrayList和HashMap的結合使用

ArrayList和HashMap的結合使用

2.分析以下需求,並用程式碼實現:
 (1)利用鍵盤錄入,輸入一個字串
 (2)統計該字串中各個字元的數量
 (3)如:
  使用者輸入字串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
  程式輸出結果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)

 基本解決思路:
    1,用ArrayList接收輸入的字元
    2,對輸入的字串轉換成字元陣列,統計各個字元的總出現數,
    3,將 字元:字元個數    儲存到hashMap中
    4,遍歷輸入hashmap表即可
  

主程式大致框架:

public static void main(String[] args) {
  List<String> array = new ArrayList<String>();
  Map<Character,Integer> map = new HashMap<Character,Integer>();
  
  function_1(array);//鍵盤接收字串
  function_2(array,map);//將字串轉換成字元陣列,並將統計的字元和字元個數儲存到HashMap中
  function_3(map); //遍歷HashMap,輸出最後結果
  
 }

funciton_1()的主要程式碼如下:

	//接收字串函式,輸入字串,直到輸入  end 為止
	public static void function_1(List<String> array) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			String str = sc.next();
			if("end".equals(str)) {
				sc.close();
				break;
			}
			array.add(str);
			
		}
		
	}

function_2()的主要程式碼如下:
public static void function_2(List<String> array,Map<Character,Integer> map) {
		
		//建立字元陣列接收字串轉換過來的字元陣列
		char[] ch = array.toString().toCharArray();
		for (int i = 0; i < ch.length; i++) {
			System.out.print(ch[i]);
		}
		System.out.println("\n===================================");
		
		
		int[] number = new int[ch.length]; 
				
		//雙重for迴圈統計字元個數
		//由於String.toCharArray()是把"[","]",給算上的,所以將最開始和最後的括號去掉
		for (int i = 1; i < ch.length-1; i++) {
			int count = 1; //字元最開始有一個
			for (int j = 1; j < ch.length-1; j++) {
				if(ch[i] == ch[j])
					number[i] = count++;
			}
		}
		
		//將統計的字元個數還有數字新增到HashMap中
		//由於String.toCharArray()是把"[","]",給算上的,所以將最開始和最後的括號去掉
		for (int i = 1; i < number.length-1; i++) {
			map.put(ch[i], number[i]);
		}
	}

function_3()的主要程式碼如下:

	public static void function_3(Map<Character,Integer> map) {
		//遍歷map集合,輸出相應的鍵值對
		for(Map.Entry<Character,Integer> entry : map.entrySet()) {
			char c = entry.getKey();
			Integer in = entry.getValue();
			System.out.print(c+"("+in+")"+" ");
		}
			
	}
我的程式的執行結果如下: