The following code is the print the frequency or the total occurrence of the characters in a String entered by the user.
Code:-
import java.util.*;
public class Frequency{
Scanner scan=new Scanner(System.in);
String string;
int occurance=0, count=0, max=0, gap=0, length;
public void input(){
try{
System.out.println("Enter any String to print its Frequency: ");
string=scan.nextLine();
}
catch(Exception e){
System.out.println("Error Code: "+e);
System.exit(0);
}
}
public void compute(){
length=string.length();
System.out.println("Character\tFrequency");
for(int i=0; i<length; i++){
occurance=0;
count=1;
for(int j=i-1; j>=0; j--)
if(string.charAt(j)==string.charAt(i)){
occurance=1;
break;
}
if(occurance==0){
for(int j= i+1; j<length; j++)
if(string.charAt(j)==string.charAt(i))
count++;
}
System.out.println(" "+string.charAt(i)+"\t\t "+count);
}
}
public static void main(String[] args){
Frequency freq=new Frequency();
freq.input();
freq.compute();
}
}
Output:-
Enter any String to print its Frequency:
FREQUENCY
Character Frequency
F 1
R 1
E 2
Q 1
U 1
E 1
N 1
C 1
Y 1
Code:-
import java.util.*;
public class Frequency{
Scanner scan=new Scanner(System.in);
String string;
int occurance=0, count=0, max=0, gap=0, length;
public void input(){
try{
System.out.println("Enter any String to print its Frequency: ");
string=scan.nextLine();
}
catch(Exception e){
System.out.println("Error Code: "+e);
System.exit(0);
}
}
public void compute(){
length=string.length();
System.out.println("Character\tFrequency");
for(int i=0; i<length; i++){
occurance=0;
count=1;
for(int j=i-1; j>=0; j--)
if(string.charAt(j)==string.charAt(i)){
occurance=1;
break;
}
if(occurance==0){
for(int j= i+1; j<length; j++)
if(string.charAt(j)==string.charAt(i))
count++;
}
System.out.println(" "+string.charAt(i)+"\t\t "+count);
}
}
public static void main(String[] args){
Frequency freq=new Frequency();
freq.input();
freq.compute();
}
}
Output:-
Enter any String to print its Frequency:
FREQUENCY
Character Frequency
F 1
R 1
E 2
Q 1
U 1
E 1
N 1
C 1
Y 1
Comments