0

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));
  }
}
  • You're basically starting with `nDecimal[nDecimal.length]`. That's not valid. For any given array `x`, the highest valid index is `x.length - 1`. – Jon Skeet Apr 05 '21 at 18:05
  • change this `int size = nDecimal.length; ` by `int size = nDecimal.length - 1;` – Med Elgarnaoui Apr 05 '21 at 18:10
  • But you then want to change the lower bound to `i >= 0` as well. It's not clear why you're increasing `size` in the loop though. And you'll still get an exception because `backwards` won't be big enough with the extra commas. (Just changing size doesn't change the length of the array...) – Jon Skeet Apr 05 '21 at 18:14

0 Answers0