Search code examples
javaarraysmultidimensional-arraymessageformat

messageFormt() Error with multidimensional array


Hello I am trying to run my program but I am getting a really weird output. This program works when its a single array but when I make it a multidimensional it errors out. please help

public static void main(String[] args) throws IOException {

            MessageFormat messageFormat = new MessageFormat("insert into {0} values ( ''{1}'', ''{2}'', ''{3}'', ''{4}'' )");
            Object[][] data = { {"000", "111", "222","333","444","555"},
                               {"000", "123", "234","345","456","567"} }; 

            System.out.println(messageFormat.format(data));
}

my output is:

run:
insert into [Ljava.lang.Object;@2a134eca values ( '[Ljava.lang.Object;@52934c3b', '{2}', '{3}', {4} )
BUILD SUCCESSFUL (total time: 0 seconds)

Solution

  • MessageFormat with the format provided is perfect for printing 1-D array. Yet it cannot print 2-D array out of the box.

    You need to iterate over your 2-D array data:

    for(Object[] array : data) {
        System.out.println(messageFormat.format(array));
    }