Flare Cat Flare Cat - 1 month ago 6
Java Question

How to print an int with comma divisors using a recursive method (no strings)?

In my computer science class, we were assigned a lab on recursion in which we have to print out a number with commas separating groups of 3 digits.
Here is the text directly from the assignment (the method has to be recursive):


Write a method called printWithCommas that takes a single nonnegative
primitive int argument and displays it with commas inserted properly.
No use of String.

For example printWithCommas(12045670); Displays 12,045,670

printWithCommas(1); Displays 1


I am really stumped on this. Here is my code so far:

public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}


It gets a stack overflow (which I can fix later), but it fails to print out some of the zeros, specifically the ones that are supposed to be after each comma.

I feel like I am taking this on with a completely wrong approach, but can't think of a good one. Any help would be appreciated.

Thanks in advance!

Note:
power
is a function I made that calculates power. First argument is the base, second is the exponent.

Answer

Here is the code I came up with, for anyone else that might be stuck on this:

public static void printWithCommas(int num) {
    if (num > 999) {
        printWithCommas(num/1000);
        System.out.print(',');
        if (num % 1000 < 100) System.out.print('0');
        if (num % 1000 < 10) System.out.print('0');
        System.out.print(num%1000);
    }
    else {
        System.out.print(num);
    }
}
Comments