0

I'm trying to use some new Java string formatting tricks, pretty basic stuff. It compiles without any error messages but won't allow me to execute the code. Could someone please explain to me why this is wrong? Thanks in advance.

My code:

class TestingStringFormat {
    public static void main(String args[]) {
        System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120);

        for(int i=0; i<20; i++){
        System.out.printf("%-2d: ", i,  "some text here/n", 1);
    }
    }
}

2 Answers 2

2

In both of your printfs, the number of format specifiers does not match the number of arguments you are passing in.

For example, the first printf reads:

System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120);

It's expecting an integer followed by another integer. You are passing in a String, an int, and another int.

In your second printf:

System.out.printf("%-2d: ", i,  "some text here/n", 1);

It's expecting an integer. You are passing in an int, a String, and another int.

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

Comments

1

You're missing the format specifier that corresponds to the first String argument on the printf method so a IllegalFormatConversionException will be thrown

System.out.printf("Total cost %s %-10d ; quantity %d\n", "ten spaces", 5, 120);
                              ^

Your second printf statement will not throw a runtime exception but only the first argument will be displayed. You could do

System.out.printf("%-2d: %s %d%n", i,  "some text here/n", 1);

Read: Formatter

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.