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
        );                           
    }
}
4
  • 1
    Possible duplicate of What's the simplest way to print a Java array? Commented Oct 26, 2017 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). Commented Oct 26, 2017 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. Commented Oct 26, 2017 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. Commented Oct 26, 2017 at 14:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.