The below code is to count the occurence of each character and it should print the count. But with the code I have tried I get only a 1 I don't know the changes I should make.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
class Count_CharMap {
public static void main(String[] args) {
try
{
FileInputStream file = new FileInputStream("D:\\trial.txt");
DataInputStream dis = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String Contents="";
String str="";
while ((Contents = br.readLine()) != null) {
str+=Contents;
}
char[]char_array =str.toCharArray();
int count = 0;
char ch = char_array[count];
Map<Character,Integer> charCounter=new HashMap<Character,Integer>();
for(int i=0;i<str.length();i++)
{
if(charCounter.containsKey(char_array[i]))
{
charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
charCounter.put(ch, 1);
}
}
for(Character key:charCounter.keySet())
{
System.out.println(key+""+charCounter.get(key));
}
}
catch(IOException e1){
System.out.println(e1);
}
}
}
Actual output should be like If i have abcdabc in my trial.txt it should print a 2 b 2c 2 d 1.
Declare a Hashmap in Java of {char, int}. Traverse in the string, check if the Hashmap already contains the traversed character or not. If it is present, then increase its count using get() and put() function in Hashmap. Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.
size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.
You're leaving char ch set as the same character through each execution of the loop.
It should be:
ch = char_array[i];
if(charCounter.containsKey(ch)){
charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
charCounter.put(ch, 1);
}
Inside the for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With