1

the current code I have lists the frequency of an array of letters and I was wondering if there was a way to incorporate numbers and all punctuation available to the user. (i.e. ASCII text) I appreciate any help!

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
   Scanner scan = new Scanner(System.in);
    int i = 0; 
    int j = 0; 
    int k = 0; 
    String str;
    char c, ch;


    System.out.print("Enter a String : ");
    str=scan.nextLine();

    i=str.length();
    for(c='A'; c<='z'; c++)
    {
        k=0;
        for(j=0; j<i; j++)
        {
            ch = str.charAt(j);
            if(ch == c)
            {
                k++;
            }
        }
        if(k>0)
        {
            System.out.println( c + "  "  + k );
        }



}
}
}

input
Enter a String : jhdvaevaecvieabvuae[;;;/'[298734327
output
[  2
a  4
b  1
c  1
d  1
e  4
h  1
i  1
j  1
u  1
v  4

Also, this code all ready accommodates for upper and lower case differentiation.

Sebastian
  • 15
  • 1
  • 3
  • Just change your loop bounds to include all the characters you want to count. E.g. start with `c=' '`, keep going while `c<=127`. – Andy Turner Jul 05 '18 at 05:41

4 Answers4

0

Using java 8, you can easily handle this problem by stream and groupingBy as follows:

    import static java.util.stream.Collectors.*;

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a String : ");
    String str =scan.nextLine();
    String ret = str.chars().mapToObj(c -> (char) c).collect(groupingBy(c -> c, counting()))
            .entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getValue))
            .map(entry -> entry.getKey() + ": " + entry.getValue())
            .collect(joining(", "));
    System.out.println(ret);

Here is demo (input and output):

Enter a String : scan.nextLine();
a: 1, c: 1, s: 1, t: 1, (: 1, x: 1, ): 1, i: 1, ;: 1, L: 1, .: 1, e: 2, n: 3
Hearen
  • 7,420
  • 4
  • 53
  • 63
  • OP is struggling with basic of java and you dear boomed with such Java 8'ish –  Jul 05 '18 at 06:44
  • Lots of solutions to the same question and it's OP's choice to which. I just provide a possible one. Hope it can be helpful +: just be easy, dude – Hearen Jul 05 '18 at 06:45
0

You can use following steps. create an array of frequency having capacity as 128 ( ascii character set size). Initialise all elements of frequency to 0. Now scan each character of input string and increment the frequency by 1 in frequency array. The index of array can be computed by converting current character to its integer representation. For your reference, you can go through code provided below.

public String computeFrequency(String input) {
    int []frequecy = new int[128]; // each element of array represent frequency of some character indexed by character's ascii code
    for(char ch: input.toCharArray()) {
        int intCurrentChar = (int) ch;  // get ascii code of current character. It can be obtained by casting character to integer in java.
        frequecy[intCurrentChar]++; // increase the frequency of current character
    }

    // collect all non zero frequency to string
    StringBuilder sbr = new StringBuilder();
    for(int frequencyIndex = 0; frequencyIndex <128; frequencyIndex++) {
        if( frequecy[frequencyIndex]>0) {
            char ch = (char) frequencyIndex; // get ascii character from ascii code. It can be obtained by casting integer to character in java.
            sbr.append(ch).append(" ").append(System.lineSeparator());
        }
    }

    return sbr.toString();  
}
Naim
  • 86
  • 5
0

This is the kind of thing Maps were made for.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a String : ");
    String s = scan.nextLine();

    Map<Character, Integer> frequency = new TreeMap<>();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        Integer n = frequency.get(c);
        if (n == null) frequency.put(c, 1);
        else frequency.put(c, n + 1);
    }

    for (Map.Entry<Character, Integer> e : frequency.entrySet()) {
        System.out.println(e.getKey() + " " + e.getValue());
    }
}

Don't forget to import java.util.Map and java.util.TreeMap.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

Why bother checking like that if you want to support all characters on keyboard? (user can technically input any ASCII characters). Below is a simpler solution and gives you better time performance:

public static void main(String[] args) {
    Map<Character, Integer> rst = new HashMap<>();
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter String: ");
    String str = sc.nextLine();

    char[] charArr = str.toCharArray();

    for(int i = 0; i < charArr.length; i++){
        int cnt = rst.containsKey(charArr[i]) ? rst.get(charArr[i])+1 : 1;

        rst.put(charArr[i], cnt);
    }

    rst.entrySet().forEach(entry -> {
        System.out.println(entry.getKey() + " " + entry.getValue());
    });
}

Below is a sample run:

Enter String: 
dfasrewrqe234342#$@#%@#$%@#$
@ 3
a 1
# 4
d 1
$ 3
e 2
% 2
f 1
q 1
r 2
2 2
s 1
3 2
4 2
w 1

Process finished with exit code 0
Isaac_Zhu
  • 105
  • 10