Search code examples
javaalgorithmdebuggingkatacoda

As a newbie I can't find the bug in the program


I was training a code wars kata and the kata was:

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm with letters not from a to m.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from a to z.

Examples:

s="aaabbbbhaijjjm"
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"

and as a newbie, I tried to attempt it . My program is like this:

public class Printer {
    
    public static String printerError(String s) {
      int printErr = 0;
      char end = 110;
      int i = 0;
        while (i < s.length()){
          if(s.charAt(i) > end ){
          printErr++;
          }
          i++;
        }
        String rate = String.format("%d/%d",printErr , s.length());
        return rate;
    }
}

It passed the test but while submitting the Kata the counter was missing 1 or 2 numbers. Can anyone help?


Solution

  • This is an answer from one newbie to another :p, so my answer may be a little wrong. As far as I have understood, you have committed a silly logical error within the if-condition.

    if(s.charAt(i) > end )
    

    You have used ASCII values, which is assigned as follows: a-97, b-98, c-99..., m-109. Note that you are counting it error only if the ASCII value of character is more than 110, meaning that your code will accept 'n' (whose ASCII value is 110) to be valid. That might be the only reason why your counter would store a wrong value.