Muldawg2020 Muldawg2020 - 1 month ago 17
Java Question

counting multiple instances of a char (in a row) in a string

No idea why my code isn't working. It keeps returning a value of 1 instead of what I expect.

public class Lab5Example
{
public static void main(String[] args)
{
System.out.println(longestRun("aabbbccd"));
System.out.println("Expected 3");
System.out.println(longestRun("aaa"));
System.out.println("Expected 3");
System.out.println(longestRun("aabbbb"));
System.out.println("Expected 4");
}


public static int longestRun(String s)
{
int count = 1;
int max = 1;

for (int i = 0; i < s.length() - 1; i += 1) {
char c = s.charAt(i);
char current = s.charAt(i + 1);
if (c == current) {
count += 1;
}
else {
if (count > max) {
count = max;
}
current = c;
}
}
return max;
}
}


Debugger isn't working right so I have no idea what's not working.

Answer

I see 3 issues.

max = count should be count = max. This is so you store the highest score found thus far.

current = c should be count = 1. This is so you reset the count to start the counting over on the next char sequence.

Outside of your loop you need to do a final check to see if the last char sequence had the highest score. if(count > max) max = count;

This would all look like:

for (int i = 0; i < s.length() - 1; i += 1) {
    char c = s.charAt(i);
    char current = s.charAt(i + 1);
    if (c == current) {
        count += 1;
    }
    else {
        if (count > max) {
            max = count; // #1
        }
        count = 1; // #2
    }
}
if(count > max) // #3
    max = count;

return max;