user6179055
user6179055

Reputation:

Method for adding commas to digit string in Java

The assignment is to add comes after every three digits looking from right to left. So number 1000000 should be 1,000,000 etc.

I have relatively good idea how to tackle this problem, but I have no idea why am I getting no output. Maybe I am making some mistake that I am not aware of or something...

I think that I understand concept that Strings are immutable, so they cannot be changed in place and when you want to change something to string you have to make new string object. But I dont get how is this possible then:

`result = ch + result;` 

and this

result = "," + result;

What am I getting wrong here ?

   import acm.program.*;
   import acm.util.*;

    public class AddCommasToNumericString extends ConsoleProgram{

        public void run(){
            while(true){
                String digits = readLine("Enter a numeric string: ");
                if (digits.length() == 0) break;
                println(addCommasToNumericString(digits));
            }
        }

        public String addCommasToNumericString(String digits){
            String result = "";
            int counter = 0;
            for (int i = digits.length()-1; i <= 0 ; i--){
                char ch = digits.charAt(i);
                result = ch + result;
                counter++;
                if (counter % 3 == 0){
                    result = "," + result;
                }
            }
            return result;
        }
    }

Upvotes: 2

Views: 13125

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

I suggest eliminating the counter and use only the loop variable by making a small change:

public String addCommasToNumericString(String digits) {
    String result = "";
    for (int i=1; i <= digits.length(); ++i) {
        char ch = digits.charAt(digits.length() - i);
        if (i % 3 == 1 && i > 1) {
            result = "," + result;
        }
        result = ch + result;
    }

    return result;
}

addCommasToNumericString("123");     // 123
addCommasToNumericString("12345");   // 12,345
addCommasToNumericString("1234567"); // 1,234,567

Upvotes: 3

older coder
older coder

Reputation: 704

Convert the read line into an Integer, then format it as a String

String digits = readLine("Enter a numeric string: ");
Integer myInt = new Integer(digits);
String output = NumberFormat.getNumberInstance(Locale.US).format(myInt.value());

Upvotes: 3

Related Questions