这是我第一次使用测试驱动开发,我正在制作一个小型计算器,但使用字符串使其更有趣。然后将字符串分解,并对各个数字进行计数。
不幸的是,我在添加两个相同的数字时遇到了这个问题。顺序是2、3、7、5、3。我的前 3 个与占据数组最后位置的最后 3 个进行比较。我不断检查该字符是否是数组中的最后一个字符。但我的意思是检查定位而不是实际值本身。
请注意,字符串已经被修剪,这意味着它们不包含空格。
在使用数组之前,我使用过CharacterItorator。不幸的是,我无法管理并决定是否可以通过可靠的数组得到答案。我设法解决了其他序列,但最后一位数字是不重复的数字。
输入字符串:“2,3,7,5,3”。答案应该是 20,但结果是 23
public int inputIterator(String input){
int currentCount = 0, tempCount;
String currentString = "";
char[] chars = input.toCharArray();
for (char ch : chars){
if(ch != ','){
// it is a number
if(ch == chars[chars.length-1]) {
currentString = currentString + ch;
tempCount = Integer.parseInt(currentString);
currentCount = currentCount + tempCount;
} else {
currentString = currentString + ch;
}
} else {
// It is a ','
if(ch == chars[chars.length-1]){
tempCount = Integer.parseInt(currentString);
currentCount = currentCount + tempCount;
} else {
if(currentString != ""){
tempCount = Integer.parseInt(currentString);
currentCount = currentCount + tempCount;
currentString = "";
} else {
// do nothing
}
}
}
}
return currentCount;
}
测试期望该序列的结果为 20。但提供的答案是 23,这是因为重复的数字。
米脂
相关分类