Aamir
Aamir

Reputation: 2424

Formatting types in Java

public class T {

    public static void main(String[] args) {    
        int i = 2345;
        System.out.printf("%0-10d", i);
        System.out.printf("(%-010d)", i);
    }
}

Can somebody please explain why these two SOP's are showing run-time error.

Upvotes: 0

Views: 96

Answers (3)

femtoRgon
femtoRgon

Reputation: 33351

You are trying to use two flags that don't make sense together.

  • - left justify in the field
  • 0 left pads the number with zeroes.

You can't do both. If you left justify, there is no room for those leading zeroes.

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234847

You are specifying contradictory flags. The 0 indicates that the output should be zero-padded; the - indicates that it should be left-justified. You can't have both.

Upvotes: 2

Alexey Malev
Alexey Malev

Reputation: 6533

You get runtime error because you provided invalid format pattern.

Some examples from here:

long n = 461012;
System.out.format("%d%n", n);      //  -->  "461012"
System.out.format("%08d%n", n);    //  -->  "00461012"
System.out.format("%+8d%n", n);    //  -->  " +461012"
System.out.format("%,8d%n", n);    // -->  " 461,012"
System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

Upvotes: 1

Related Questions