Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

The below code is to count the occurrence of each character and it should print the count. But with the code, I have tried I get only a 1 and 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);

    }

    }

}

The actual output should be like if I have abcdabc in my text file  it should print a 2 b 2 c 2 d 1

1 Answer

0 votes
by (13.1k points)

You are 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.

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4k points)

Browse Categories

...