0

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

3
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by stultuske
0

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

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

1

try by turning your split method call in:

String[] formatA = number.split("\\.");
Votes + Comments
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));

Edited by NormR1

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.