Skip to content

Instantly share code, notes, and snippets.

@lisakstep
Created February 8, 2014 16:54
Show Gist options
  • Save lisakstep/8886613 to your computer and use it in GitHub Desktop.
Save lisakstep/8886613 to your computer and use it in GitHub Desktop.
This file adds commas in the US style to user-entered numbers. Stanford CS106a assignment 4.1
/** This class adds commas in the US style to user-entered numbers
* @author Lisa Stephens February 6, 2014
* Complete
* written as a response to Stanford CS 106a exercise 4.1
* The run() method was essentially given by the assignment.
*/
import acm.program.ConsoleProgram;
public class AddCommas extends ConsoleProgram{
public void run(){
while (true) {
String digits = readLine("Enter a numeric string: ");
if (digits.length() == 0 ) {
println("Done");
break;
}
println(addCommasToNumericDigits(digits) );
}
}
private String addCommasToNumericDigits(String number) {
// Working backward from the digits in the string, build the new string, adding
// commas when appropriate
String newNumberWithCommas = "";
for (int i = 0; i< number.length(); i++) {
char ch = ( number.charAt(number.length() - 1 - i) );
newNumberWithCommas = ch + newNumberWithCommas;
if ( ( ( (i+1) % 3) == 0 ) && ( (i+1) < number.length()) ) {
newNumberWithCommas = "," + newNumberWithCommas;
}
}
return newNumberWithCommas;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment