I want to format an output string with a series of variables. When I use an array of strings, this works as expected:
String[] myArray = new String[3];
// fill array with strings
System.out.printf("1: %s \n2: %s \n3: %s\n", myArray);
I want to use this to print the results of simulated dice-throws, so I use an array of ints. However, this doesn’t work:
int[] myArray = new int[3];
// fill array with numbers
System.out.printf("1: %d \n2: %d \n3: %d\n", myArray);
Exception in thread "main" java.util.IllegalFormatConversionException: d != [I
Of course, I could use myArray[0] etc. for every element, but this doesn’t seem very elegant.
Why is this so and how can I achieve the desired result?
printfis a variable argument method that takes aString(the format string) and an arbitrary number of arguments (to be formatted).Varargs are implemented as arrays in Java.
printfexpectsObjectas its varargs type, therefore the internal type isObject[].A
String[]is-aObject[](i.e. it can be cast to that type), so the elements of theString[]will be interpreted as the separate arguments.An
int[]however, can’t be cast to anObject[]so theint[]itself will be the first (and only) element of the varargs array.Then you try to format the
int[]using%dwhich won’t work, because anint[]is not a (single) decimal number.