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

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