Skip to content

Instantly share code, notes, and snippets.

@cored
Created November 27, 2009 14:08
Show Gist options
  • Save cored/244032 to your computer and use it in GitHub Desktop.
Save cored/244032 to your computer and use it in GitHub Desktop.
/* StringCalculator Code Kata - I found my solution as beautiful code, even though i will try to get it better */
public class StringCalculator {
private static final String DELIMITER = "//";
public int add(String numbers) {
if (isNumbersEmpty(numbers)) {
return 0;
}
handleNegativeNumber(numbers);
if (hasDelimiter(numbers)) {
if (hasMoreThanOneNumber(numbers, substractDelimiter(numbers))) {
return addMoreThanTwoNumbers(numbers, substractDelimiter(numbers));
}
} else {
return addMoreThanTwoNumbers(numbers);
}
return handleOneNumber(numbers);
}
private void handleNegativeNumber(String numbers) {
if (isNumbersNegative(numbers)) {
throw new IllegalArgumentException("Negative number not allowed - "
+ numbers);
}
}
private boolean isNumbersNegative(String numbers) {
return numbers.contains("-");
}
private boolean hasMoreThanOneNumber(String numbers, String delimiter) {
return numbers.contains(delimiter);
}
private int handleOneNumber(String numbers) {
return Integer.parseInt(numbers);
}
private boolean isNumbersEmpty(String numbers) {
return "".equals(numbers);
}
private int addMoreThanTwoNumbers(String numbers, String substractDelimiter) {
numbers = numbers.substring(4, numbers.length());
return addNumbers(numbers, substractDelimiter);
}
private int addMoreThanTwoNumbers(String numbers) {
numbers = numbers.replaceAll("\n", ",");
return addNumbers(numbers, ",");
}
private String substractDelimiter(String numbers) {
return numbers.substring(2, 3);
}
private boolean hasDelimiter(String numbers) {
return numbers.startsWith(DELIMITER);
}
private int addNumbers(String numbers, String delimiter) {
int result = 0;
for (String number : numbers.split(delimiter)) {
result += handleOneNumber(number);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment