I'm trying to create a code that formats an integer, n, to have commas where appropriate. For example, 5000 becomes 5,000. To do this I am reversing the array so that I have commas every 3 spaces from the last digit, then reversing the array again for printing. The output for the default formatter, which prints the number out without formatting, is correct but the output for the decimal formatter is giving an error which states
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at DecimalSeparatorFormatter.format(Format.java:22) at Format.main(Format.java:50)
interface NumberFormatter {
public String format(int n);
}
class DefaultFormatter implements NumberFormatter {
public String format(int n)
{
return String.valueOf(n);
}
}
class DecimalSeparatorFormatter implements NumberFormatter {
public String format(int n)
{
char [] nDecimal = String.valueOf(n).toCharArray();
int size = nDecimal.length;
char [] backwards = new char[size];
int j = 0;
for (int i=size; i > 0; i--)
{
backwards [j] = nDecimal[i];
if (j%4 == 0)
{
backwards [j] = ',';
j++;
size++;
backwards [j] = nDecimal[i];
}
j++;
}
int backSize = backwards.length;
int l = 0;
char [] nDecPrint = new char [backSize];
for (int k = backSize; k > 0; k--)
{
nDecPrint[l] = backwards[k];
l++;
}
String arrString = String.valueOf(nDecPrint);
return arrString;
}
}
public class Format {
public static void main(String[] args) {
int n = 5000;
DefaultFormatter numDef = new DefaultFormatter();
System.out.println(numDef.format(n));
DecimalSeparatorFormatter numDec = new DecimalSeparatorFormatter();
System.out.println(numDec.format(n));
}
}