I have this code:

 static String format(String number, int decimalLength) {
        char[] decimal;
        String[] formatA = number.split(".");
        StringBuilder cents = new StringBuilder("");
        int dollars = 0;
        dollars = Integer.parseInt(formatA[0]);
        decimal = formatA[1].toCharArray();
        for (int i = 0; i < decimal.length; i++) {
            if (i < decimalLength) {
        String moneyString = "$" + dollars + "." + cents;
        return moneyString;

It looks fine to me, and yet this is the output I get:
Error Output: java.lang.ArrayIndexOutOfBoundsException: 0
BUILD SUCCESSFUL (total time: 0 seconds)

Note: the line "Error output" is from an exception handler I created, the rest is coming from print statements within this method

java.lang.ArrayIndexOutOfBoundsException: 0

What line does that error happen on? The message says that the array is defined with 0 elements and does not have a first element at index=0

the input is format("323.90905",2);
it looks like formatA is never getting it's two piece array (in line 4) like I'd expect and then when its called in line 8 the exception gets thrown

Print out the contents of formatA using the Arrays class's to String() method to format it for printing. Them you'll know what split() is doing.

An example: System.out.println("res="+java.util.Arrays.toString(result));

Edited 4 Years Ago by NormR1

no problem. if it's fixed, just mark the thread as solved, so others 'll know they don't have to search for an alternate sollution :)

This question has already been answered. Start a new discussion instead.