I have this code:

 static String format(String number, int decimalLength) {
        char[] decimal;
        System.out.println(number);
        String[] formatA = number.split(".");
        System.out.println(formatA.length);
        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) {
                cents.append(decimal[i]);
            }
        }
        String moneyString = "$" + dollars + "." + cents;
        return moneyString;
    }

It looks fine to me, and yet this is the output I get:
323.90905
Error Output: java.lang.ArrayIndexOutOfBoundsException: 0
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

Recommended Answers

All 7 Replies

what is the input you give?

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

try by turning your split method call in:

String[] formatA = number.split("\\.");
commented: That's seems to be what was wrong +0

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));

Thanks, that worked.

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.