简体   繁体   中英

Count Occurrence of each letter in a loop and display with letter with the most number of occurences

I'm having trouble in using this code I found on the net. my goal is to count the number of times a letter show and display the letter with the most occurrence and if there are 2 or more letters that occurred at the same number of times then they will both show up.

This is my current output: Current Output

Here is the code i found on the net and working with:

public void fcount(String str)
{

int[] occurence = new int[255];
   // Scanner scanner = new Scanner(System.in);
// str = scanner.nextLine();

// optional to put eveyting in uppercase
str = str.toUpperCase();
// convert to char
char[] digit = str.toCharArray();
// count
for(int i = 0; i < digit.length; i++)

    occurence[digit[i]]++;
// find max
int max = 0;           // max value
char maxValue = 0;      // max index
for(int i = 0; i < occurence.length; i++) 

    {
   // new max ?
   if(occurence[i] > max) {
      max = occurence[i];
      maxValue = (char) i;
   }
}
// result
System.out.println("Character used " + max + " times is: " + (char) maxValue);
   // return "";
}

And Here is the the loop where i'm using it:

public void calpha()
{

char startUpper = 'A';
String cones = null;

for (int i = 0; i < 12; i++) {

    cones = Character.toString(startUpper);
    System.out.println(startUpper);

}
fcount(cones);

}

There is an error in you loop:

cones = Character.toString(startUpper);

You are just re-assigning the value of cones , so fcount receives a string containing only the last character.

A solution is

cones += Character.toString(startUpper);

Try this code:

public static void main(String[] args) throws IOException {
    char startUpper = 'A';
    String cones = "";
    for (int i = 0; i < 12; i++) {
        cones += Character.toString(startUpper);
        System.out.println(startUpper);
    }
    fcount(cones);
}

public static void fcount(String str) {
    HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
    HashSet<Character> letters = new HashSet<Character>();
    str = str.toUpperCase();
    //Assume that string str minimium has 1 char
    int max = 1;
    for (int i = 0; i < str.length(); i++) {
        int newValue = 1;
        if (hashMap.containsKey(str.charAt(i))) {
            newValue = hashMap.get(str.charAt(i)) + 1;
            hashMap.put(str.charAt(i), newValue);

            if (newValue>=max) {
                max = newValue; 
                letters.add(str.charAt(i));
            }
        } else {
            hashMap.put(str.charAt(i), newValue);
        }           
    }

    System.out.println("Character used " + max + " times is: " + Arrays.toString(letters.toArray()));
    // return "";
}

You have an issue in your int[] occurence = new int[255]; statement and usage: occurence[digit[i]]++ may lead to IndexOutOfBoundsException since char type is up to 2^16

Your code can not deal with non-ANSII characters. Mine does.

import java.util.*;

class Problem {
    public static void main(String args[]) {
        final String input = "I see trees outside of my window.".replace(" ", "");

        final List<Character> chars = new ArrayList<>(input.length());
        for (final char c : input.toCharArray()) {
            chars.add(c);
        }

        int maxFreq = 0;
        final Set<Character> mostFrequentChars = new HashSet<>();
        for(final char c : chars) {
            final int freq = Collections.frequency(chars, c);
            if (freq > maxFreq) {
                mostFrequentChars.clear();
                mostFrequentChars.add(c);
                maxFreq = freq;
            }
            else {
                if (freq == maxFreq) {
                    mostFrequentChars.add(c);
                }
            }
        }

        for (Character c : mostFrequentChars) {
            System.out.println(c);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM