Skip to content

Instantly share code, notes, and snippets.

@tgruber5150
Created December 5, 2012 02:36
Show Gist options
  • Save tgruber5150/4211612 to your computer and use it in GitHub Desktop.
Save tgruber5150/4211612 to your computer and use it in GitHub Desktop.
This program pulls numbers out of a string and totals them
import org.junit.Test;
public class BetterProgrammingTaskTest extends junit.framework.TestCase {
public static String numbers = "5 25 35 5" ;
@Test
public void testGetSumOfNumbers() throws Exception {
assertEquals(70, BetterProgrammingTask.getSumOfNumbers(numbers));
}
}
public class BetterProgrammingTask {
public static int getSumOfNumbers(String s) {
/*
Please implement this method to
return the sum of all integers found in the parameter String. You can assume that
integers are separated from other parts with one or more spaces (' ' symbol).
For example, s="12 some text 3 7", result: 22 (12+3+7=22)
*/
String[] newNumbers = s.split(" ");
//Printing the new string to see what it looks like.
for (int i = 0; i < newNumbers.length; i++) {
if (i==0) System.out.print("numbers array before addition loop: " + newNumbers[i] + ", ");
else {System.out.print (newNumbers[i] + ", ");
} }
System.out.println();
int a = 0;
for (int i=0; i < newNumbers.length; i++) {
System.out.print (newNumbers[i] + ", ");
Integer j = Integer.parseInt(newNumbers[i]);
a = a + j;
}
return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment