0

I'm trying to print every element in a character array.

Why am I getting an IllegalFormatConversionException?

public class printf_function_test {     
    public static void main(String[] args) {
        int any = 5;
        String object = "car";
        char[] ch = {'3','5','6','9'};
        System.out.println(ch);
        System.out.printf(
            "%d anything can happen anytime ,bought a %s and write"
            + "this number now %c",
            any,
            object,
            ch
        );                           
    }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • 1
    Possible duplicate of [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Bernhard Barker Oct 26 '17 at 13:37
  • @Dukeling I don't think that is a duplicate, as OP's main issue is with the `String` **format** representation of a single `char` vs. a `char[]` rather than the `String` representation of the array (although the question you point at is indeed relevant). – Mena Oct 26 '17 at 13:38
  • @Mena I mostly see the issue with string formatting as something unlikely to be helpful to future visitors (because many other combinations of invalid inputs can cause the exception and this specific combination seems illogical based on the docs, but I do think a canonical post on the exception might be helpful), thus I feel the question boils down to printing an array. – Bernhard Barker Oct 26 '17 at 13:44
  • @Dukeling I see your point, but the real issue here is that a `%something` format is not suitable for a `something[]`. The issue about "how do I print a human-readable `something[]`" is secondary to the main issue in my opinion. – Mena Oct 26 '17 at 14:08

1 Answers1

2

You are passing a char[] as a single char format %c.

An array in Java is an Object, and should be formatted as its String representation (so %s).

In your case, since a default String representation of an array is unlikely to be what you want, you could use a combination of %s and pass it Arrays.toString(ch) or String.valueOf(ch) (thanks Axel).

Mena
  • 47,782
  • 11
  • 87
  • 106