Skip to content
Advertisement

Count Character Consecutively in Java

I’m trying to write a method that returns the number of times char c first appears consecutively in s, even if it’s a single occurrence of the character. Even spaces break the consecutive count. So the string “I’m bad at programming.” should only return 1, if char c was ‘a’.

The code below compiles but doesn’t print the correct answers. Just something to show my general logic when it comes to approaching this problem.

JavaScript

I just need a few pointers (logic-wise or code). Maybe there’s a method for Strings that I’ve never seen before that could make my program much simpler. I have very limited knowledge in programming and in Java.

EDIT: For anyone wondering if this is part of some homework assignment or whatnot, this was a question from a very old midterm. I got it wrong but for some reason but never bothered to ask for the correct answer at the time. I looked at it today and wanted to see if I knew the answer. Looks like I don’t.

Advertisement

Answer

Add a flag, and break out of the loop when you have found one matching character, then find “anything else”. Maybe not the most compact or elegant, but true to the original code. Tested, and produces 2,0,1,5 as expected.

JavaScript

It occurs to me that counter>0 is an equivalent condition to foundOne==true; that would allow you to simplify the code to:

JavaScript

The logic is a tiny bit harder to follow this way, as the variable name foundOne is self-documenting. But per other posts, “small is beautiful” too…

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement