Map collection of computing the number of characters in the string that appears

Exercise:

Every character in the string, computing a number of times

Analysis:
1. Scanner obtain user input string
2. Create Map set, key is a string of characters, value is the number of characters
3. Traversal string, each character acquired
4. using the acquired character, Map collection to determine whether there is key

  • key exists:
  • By character (key), to obtain value (the number of characters)
  • value++
  • put (key, value) to the new value stored in the Map collection
  • key does not exist:
  • put(key,1)

5. Map traversal set, the output

Code

Package Penalty for demo03; 

Import java.util.HashMap;
 Import java.util.Scanner; 

/ * 
    Exercise: 
        the number of calculations for each character appears in a string 

    analysis: 
        1. Scanner captures user input string 
        2. Create a Map collection, key is a string of characters, value is the number of characters 
        3. traversal string, each character acquired 
        4. characters acquired, the key to determining whether there is a set of Map 
            key exists: 
                by the character (key), obtaining value ( number of characters) 
                value ++ 
                pUT (key, value) the value is stored in the new collection Map 
            key does not exist: 
                pUT (key,. 1) 
        5. the traverse Map set, the output 
 * / 
public  class Demo03MapTest {
     public  static  voidmain (String [] args) {
         // 1. Scanner using the acquired user input string 
        Scanner SC = new new Scanner (the System.in); 
        System.out.println ( "Enter a string:" ); 
        String STR = sc.next ();
         // 2. Create Map set, key is a string of characters, value is the number of characters in 
        the HashMap <character, Integer> Map = new new the HashMap <> ();
         // 3. traversal string acquiring each character 
        for ( char C: str.toCharArray ()) {
             // 4. acquired using characters, set to Map key determines whether or not there 
            iF (map.containsKey (C)) {
                 // key exists 
                Integer value =as map.get (C); 
                value ++ ; 
                map.put (C, value); 
            } the else {
                 // Key absence 
                map.put (C,. 1 ); 
            } 
        } 
        // 5. The traverse Map set, the output 
        for (Character Key: map.keySet ()) { 
            Integer value = as map.get (Key); 
            System.out.println (Key + "=" + value); 
        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/wurengen/p/11247441.html