Changing the format specifier in the printf () method results from IllegalFormatFlagsException

advertisements

In the following code, after changing the format specifier in the printf() method from %04d%n to %0-4d%n, and running the code results in

Exception in thread "main" java.util.IllegalFormatFlagsException:

Flags = '-0'

The complete source code is as follows:

public class MinArray {

    public static void main(String[] args) {

        byte[] storeMinimum = new byte[5];
        byte[] trialArray = new byte[15];

        for(byte bt=0; bt < storeMinimum.length; bt++){
            randomize(trialArray);
            storeMinimum[bt] = findMinimum(trialArray);
        }

        for (byte minValue : storeMinimum)
            System.out.printf("%0-4d%n", minValue);

    }

    private static byte findMinimum(byte[] valArray) {
        byte minValue = valArray[0];

        for(byte bt=0; bt < valArray.length; bt++)
            minValue = (byte) Math.min(minValue, valArray[bt]);

        return minValue;
    }

    private static void randomize(byte[] valArray) {
        for (byte bt = 0; bt < valArray.length; bt++)
            valArray[bt] = (byte) (Math.random()*128);
    }

}

Can someone explain, how this could have happened, since I wanted the byte literal to be displayed as left-justified with 4 character positions? Also, please do suggest a fix for the same.


I think when you write

System.out.printf("%04d%n", minValue);

It's right-justified. All the empty space in left will replaced by '0'.

The '-' is used for left-justified.

They can't be used together.