0

I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.

E.G.

Input String:

aaaabb

Output String:

a4b2

Input String:

aaaaabbbc

Output String:

a5b3c1

I am posting my java code.
It is throwing StringOutOfBoundException

/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/

import java.util.Scanner;

public class CountingOccurences {

public static void main(String[] args) {

    Scanner inp= new Scanner(System.in);
    String str;
    char ch;
    int count=0;
    
    System.out.println("Enter the string:");
    str=inp.nextLine();
    
    while(str.length()>0)
    {
        ch=str.charAt(0);
        int i=0;
        
        while(str.charAt(i)==ch)
        {
                count =count+i;
                i++;
        }
        
        str.substring(count);
        System.out.println(ch);
        System.out.println(count);
    }

}

}
Community
  • 1
  • 1
Chitransh Saurabh
  • 377
  • 6
  • 12
  • 23

7 Answers7

3

This is the problem:

while(str.charAt(i)==ch)

That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:

while (i < str.length() && str.charAt(i) == ch)

You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change

count = count + i;

to either:

count++;

... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.

However, then your program will loop forever, as this doesn't do anything useful:

str.substring(count);

Strings are immutable in Java - substring returns a new string. I think you want:

str = str.substring(count);

Note that this will still output "a2b2a2" for "aabbaa". Is that okay?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Then how do i compare if the characters are the same.. – Chitransh Saurabh May 25 '12 at 05:59
  • Even then it is giving the same exception.. – Chitransh Saurabh May 25 '12 at 06:03
  • @user1262062: It really shouldn't be. Are you sure you've rebuilt the code? – Jon Skeet May 25 '12 at 06:04
  • @user1262062: The incorrect use of `count` would have messed it up too - see my edits. – Jon Skeet May 25 '12 at 06:07
  • Yes, I have cleaned and rebuild the code... Now it is going to an infinite loop.. Could u plz give the code u hv correctede... – Chitransh Saurabh May 25 '12 at 06:08
  • 2
    @user1262062: I've given you enough hints now, I think. I assume this is homework - I've told you everything you should need to fix it. You need to put in effort yourself to work out what's going wrong - if I just give you the complete code, you won't learn much, will you? (I'd also strongly suggest that you work on communicating using full words rather than "text-speak" which makes everyone's life harder. Communication is incredibly important in software engineering.) – Jon Skeet May 25 '12 at 06:09
  • Thnx.. i got it..thnx a lot !! – Chitransh Saurabh May 25 '12 at 06:10
  • Yeah.. I will keep that in mind !! By the way, it was not homework, I am preparing for my coding interviews and am really thankful to people like u for the help.. Again thanks a lot !!! – Chitransh Saurabh May 25 '12 at 06:22
  • 2
    If this is an answer for your interview, you have to impress the company with the best and simplest code to understand. Perfection may not be expected, but I know there's an easier code solution (see my answer below). A link is at www.careercup.com. – The Original Android May 25 '12 at 06:59
3
public class StringTest{
public static void main(String[] args){

    String s ="aaabbbbccccccdd";
    String result="";
    StringBuilder sb = new StringBuilder(s);


    while(sb.length() != 0){
        int count = 0;
        char test = sb.charAt(0);
        while(sb.indexOf(test+"") != -1){
            sb.deleteCharAt(sb.indexOf(test+""));
            count++;
        }
        //System.out.println(test+" is repeated "+count+" number of times");
        result=result+test+count;
    }
    System.out.println(result);         
}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
2

I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.

Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.

Remember, making things simple counts. Life for developers is hard enough looking at complex code.

Have fun!

Tommy "I should be a Teacher" Kwee

The Original Android
  • 6,147
  • 3
  • 26
  • 31
0

if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.

If it is a study project then keep at it and learn from your exploring :)

Steve Atkinson
  • 1,219
  • 2
  • 12
  • 30
-1

You should be able to utilize the StringUtils class and the countMatches() method.

public static int countMatches(String str, String sub)

Counts how many times the substring appears in the larger String.

Try the following:

int count = StringUtils.countMatches("a.b.c.d", ".");
Robert
  • 8,717
  • 2
  • 27
  • 34
pachun
  • 926
  • 2
  • 10
  • 26
-1

I think what you are looking for is this:

public class Ques2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = br.readLine().toLowerCase();
    StringBuilder result = new StringBuilder();
    char currentCharacter;
    int count;

    for (int i = 0; i < input.length(); i++) {
        currentCharacter = input.charAt(i);
        count = 1;
        while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
            count++;
            i++;
        }
        result.append(currentCharacter);
        result.append(count);
    }

    System.out.println("" + result);
}

}

fiddle
  • 1,095
  • 5
  • 18
  • 33
-2

Try this:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}
  • 1
    Instead of just providing code, you should try to explain what you have done so that the person asking the question can learn, and not just copy your code. – Hannes Ovrén Dec 24 '13 at 11:05