Created
April 8, 2015 13:12
-
-
Save kenechiokolo/b83d130a0cab8e1d8bea to your computer and use it in GitHub Desktop.
Section Handout #4 - 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import acm.program.*; | |
public class String_Methods extends ConsoleProgram { | |
public void run() { | |
while (true) { | |
String digits = readLine("Enter a numerical string: "); | |
if (digits.length() == 0) break; | |
println(addCommasToNumericString(digits)); | |
} | |
} | |
private String addCommasToNumericString(String digits) { | |
int nDigits = digits.length(); // creates integer counting the number of digits | |
String delimString = digits; // string delimited by commas, initialised equivalent to digits | |
while (nDigits > 3) { | |
String afterComma = delimString.substring(nDigits - 3); // substring containing every char after 3rd from last | |
// delimString = everything before 3rd from last char + ',' + everything after 3rd from last char | |
delimString = digits.substring(0, nDigits - 3) + ',' + afterComma; | |
nDigits -= 3; // tells program to discount last 3 digits (as comma has now been added) | |
} | |
return delimString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment