I want to make it so that the code only adds completely unique versions of the number I am trying to read (ie. 1 in 111 gives out 3, but 33 in 333 only gives out 33.), but when I try to output the result, instances like the latter example count up once every interval and add each instance counted (33 in 333 gives out 66 instead of 33, for example).
Here is my code so far:
public static int sumRepeat(int num, String text)
{
int sum = 0;
String calc = Integer.toString(num);
int value = text.indexOf(calc);
for (int i = 0; i < text.length() - calc.length() + 1; i++) {
if (text.substring(i, i + calc.length()).equals(calc))
sum += num;
}
return sum;
}
Could someone help me get it to where I do not run into this error and the code runs as intended? Thank you.
Edit: Apologies, but I have more test cases than I initially said I had. Here are all of my test cases:
sumRepeat(1, "I love CSCE111") returns 3
sumRepeat(12, "The bill is $12.97") returns 0
sumRepeat(33, "333 bananas for 33 monkeys.") returns 66
sumRepeat(333, "My number is (333)-333-3333") returns 999
sumRepeat(87, "I can't believe Aragorn is 83 years old. 83!") returns 0
sumRepeat(41, "41414141") returns 164
sumRepeat(0, "") returns 0