Why does the last char doesn’t appear?

I want to encode a String like ...----....--.-.-. to .3-4.4-2.1-1.1-1.1 – showing, that there are three dots first (.3), then four hyphens (-4) next and so on.

I nearly made it, but there’s a mistake anywhere…

static String pointsAndLines(String s){

    StringBuffer encodedString = new StringBuffer();

    int counter = 1;
    char currentChar = s.charAt(0);

    for(int i=1; i<s.length(); i++){
        if(s.charAt(i) != currentChar){
            encodedString.append(String.valueOf(currentChar) + counter);
            currentChar = s.charAt(i);
            counter = 1;
        } else counter++;
    }

    return encodedString.toString();

}

But the output is this:

.3-4.4-2.1-1.1-1

The last .1 is missing – but why?

Answer

The loop is terminated once you hit the end of the string, and the last group isn’t appended to the buffer. You could just explicitly append it:

for(int i=1; i<s.length(); i++){
    if(s.charAt(i) != currentChar){
        encodedString.append(String.valueOf(currentChar) + counter);
        currentChar = s.charAt(i);
        counter = 1;
    } else counter++;
}
encodedString.append(String.valueOf(currentChar) + counter); // Here

Leave a Reply

Your email address will not be published. Required fields are marked *