Home > Software design >  Java Substring No Errors but Doesn't Work
Java Substring No Errors but Doesn't Work

Time:01-22

I think that it should be displaying thhiisssaapre at the end, but it's not. Why is this not printing?

After getting the code to print thhiisssaapre, I plan to amend the code to produce the character frequencies. Ex: 1t 2h 2i 3s 2a 1p 1r 1e

Java Code

public class LetterFrequencies {
    public static void main(String[] args) {
        String letters = "abcdefghijklmnopqrstuvwxyz";
        String phrase = "This is a phrase!";
        String collection = "";
        System.out.println("The following shows the letter frequencies for the phrase.\n\nThe phrase is \"This is a phrase!\"");
        phrase = phrase.toLowerCase();
        for (int i = 0; i < letters.length(); i  ) {
            int h = i;
            String lettersLetter = letters.substring(h, h  );
            for (int j = 0; j < phrase.length(); j  ) {
                int k = j;
                String phraseLetter = phrase.substring(k, k  );
                if (lettersLetter.equals(phraseLetter)) {
                    collection  = phraseLetter;
                }
            }
        }
        System.out.println(collection);
    }
}

Code Output

The following shows the letter frequencies for the phrase.

The phrase is "This is a phrase!"

//this is just a blank line; it should be printing thhiisssaapre here but it's not

CodePudding user response:

I'm not sure about your question, You want to know how many times a letter appears in a sentence? If so you should try this :

    public static void main(String[] args) {
        final String phrase = "This is a phrase!".toLowerCase(Locale.ROOT);
        final Map<Character, Integer> map = new HashMap<>();

        //for each all char in your sentence
        for (char a : phrase.toCharArray()) {
            //for all char a to z
            for (char b = 'a'; b < 'z'; b  ) {
                if (a == b) {
                    //if the char is already in the map, increment the value
                    if (map.containsKey(a)) {
                        map.put(a, map.get(a)   1);
                        //if not, just put it in the map
                    } else {
                        map.put(a, 1);
                    }
                }
            }
        }

        for (char c : map.keySet()) {
            System.out.println(c   " "   map.get(c));
        }

    }

CodePudding user response:

public static String printLetterFrequencies(String source) {
    return source.chars()
            .mapToObj(ch -> (char) ch)
            .collect(groupingBy(identity(), counting()))
            .entrySet().stream()
            .map(entry -> ""   entry.getKey()   entry.getValue())
            .collect(Collectors.joining(" "));
}
  •  Tags:  
  • Related