Printer Errors

来源:互联网 发布:中北大学软件学院 编辑:程序博客网 时间:2024/06/10 09:06

Description:

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, then one time color a…

Sometimes there are problems: lack of colors, technical malfunction and a “bad” control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm.

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"

My Solution:

public static String printerError(String s) {        int errors = 0;     //打印出错的次数        int all = 0;        //字符串 s 的长度                     String result = "";        String box = "";    //装载字符串 "abc...jklm"                String[] split = s.split("");//字符串 s 转换为字符串数组 split        //将 a 到 m 的字符保存到 字符串 box 中        for (int i = 0; i < 'm' - 'a' + 1; i++) {            box += (char)('a' + i);        }        String[] boxes = box.split(""); //字符串 box 转换为字符串数组 boxes        for (int i = 0; i < s.length(); i++) {            all += 1;            if (split[i].compareTo(boxes['m' - 'a']) > 0) {                 errors += 1;            }        }        result += errors + "/" + all;        return result;    }

Notes:

java中的compareTo方法,返回参与比较的前后两个字符串的asc码的差值。

例如

  • 单个字符的字符串比较

如果

String a = "a",String b = "b";System.out.println(a.compareTo.b);

则输出-1;

如果

String a = "a",String b = "a";System.out.println(a.compareTo.b);

则输出0;

如果

String a = "b",String b = "a";System.out.println(a.compareTo.b);

则输出1;

  • 多个字符的字符串的比较

如果

String a = "ab",String b = "b";System.out.println(a.compareTo.b);

则输出-1;

如果

String a = "abcdef",String b = "b";System.out.println(a.compareTo.b);

则输出-1;
也就是说,如果两个字符串首字母不同,则该方法返回首字母的asc码的差值;

如果两个字符串首字母相同

如果

String a = "ab",String b = "a";System.out.println(a.compareTo.b);

则输出1;

如果

String a = "abcdef",String b = "a";System.out.println(a.compareTo.b);

则输出5;

如果

String a = "abcdef",String b = "abc";System.out.println(a.compareTo.b);

则输出3;

如果

String a = "abcdef",String b = "ace";System.out.println(a.compareTo.b);

则输出-1;
即参与比较的两个字符串如果首字符相同,则比较下一个字符,直到有不同的为止,返回该不同的字符的asc码差值,如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值

0 0