Why does the last char doesn’t appear? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why does the last char doesn’t appear? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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
We are here to answer your question about Why does the last char doesn’t appear? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji