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.
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();
}