作为新手,我无法在程序中找到错误 [英] As a newbie I can't find the bug in the program
问题描述
我当时正在训练代码战卡塔,而卡塔是:
I was training a code wars kata and the kata was:
在工厂,打印机会打印盒子的标签.对于一种盒子,打印机必须使用颜色,为了简单起见,用从a到m的字母命名.
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.
打印机使用的颜色记录在控制字符串中.例如好"字样.控制字符串将为aaabbbbhaijjjm,这意味着打印机使用了三种颜色a,四种颜色b,一种颜色h然后一种颜色a ...
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...
有时会出现问题:颜色不足,技术故障和坏"的现象.产生控制字符串,例如aaaxbbbbyyhwawiwjjjwwm的字母不是从a到m.
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.
您必须编写一个函数printer_error,给定一个字符串将输出打印机的错误率作为一个字符串,该字符串表示一个有理数,其分子是错误数,而分母是控制字符串的长度.不要将此分数简化为更简单的表达式.
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.
该字符串的长度大于或等于1,并且仅包含从a到z的字母.
The string has a length greater or equal to one and contains only letters from a to z.
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;
}
}
它通过了测试,但是在提交Kata时,计数器缺少1或2个数字.有人可以帮忙吗?
It passed the test but while submitting the Kata the counter was missing 1 or 2 numbers. Can anyone help?
推荐答案
实际上,您可以仅使用<
和>
来检查字符是否在Java中.您的逻辑是正确的-但由于您是新手",因此已使用while循环重新创建了for循环的功能.无需这样做-这就是我们有for循环的原因.
You can actually just use <
and >
to check if a character is in some range in java. Your logic is sound - but since you are a "newbie", you have re-created the functionality of a for-loop with your while loop. No need to do this - that's why we have for-loops.
请参阅下面的调整方法:
See the adjusted method below:
public String printerError(String s) {
int printErr = 0;
for (int i = 0; i < s.length(); i++) {
// assuming the input rules hold true, we really only need the second condition
if (s.charAt(i) < 'a' || s.charAt(i) > 'm') {
printErr++;
}
}
return String.format("%d/%d", printErr, s.length());
}
这篇关于作为新手,我无法在程序中找到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!