這是我第一次使用測試驅(qū)動(dòng)開發(fā),我正在制作一個(gè)小型計(jì)算器,但使用字符串使其更有趣。然后將字符串分解,并對各個(gè)數(shù)字進(jìn)行計(jì)數(shù)。不幸的是,我在添加兩個(gè)相同的數(shù)字時(shí)遇到了這個(gè)問題。順序是2、3、7、5、3。我的前 3 個(gè)與占據(jù)數(shù)組最后位置的最后 3 個(gè)進(jìn)行比較。我不斷檢查該字符是否是數(shù)組中的最后一個(gè)字符。但我的意思是檢查定位而不是實(shí)際值本身。請注意,字符串已經(jīng)被修剪,這意味著它們不包含空格。在使用數(shù)組之前,我使用過CharacterItorator。不幸的是,我無法管理并決定是否可以通過可靠的數(shù)組得到答案。我設(shè)法解決了其他序列,但最后一位數(shù)字是不重復(fù)的數(shù)字。輸入字符串:“2,3,7,5,3”。答案應(yīng)該是 20,但結(jié)果是 23public 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; }測試期望該序列的結(jié)果為 20。但提供的答案是 23,這是因?yàn)橹貜?fù)的數(shù)字。
1 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
那么問題一定出在你的邏輯上。您會(huì)考慮使用基于流的較短函數(shù)嗎?例如:
public int sumFromString(String input) {
return Arrays.stream(input.split(","))
.mapToInt(Integer::parseInt)
.sum();
}
添加回答
舉報(bào)
0/150
提交
取消