Using parameter for specific width

I want the second parameter in prettyInt to be the width in front of the first parameter. I do not know how to put a variable into a String.format at the %. Could someone help me?

public  class SomeFormats {

    public static void main (String[]args) {
        PrintWriter out = new PrintWriter (System.out);
        prettyInt(10, 30);
        out.flush();
    }

    public static String prettyInt(int n, int width) {
        int i = width;
        return String.format("%i %d", n);
    }
}

>Solution :

You just have to concatenate width value inside your String.

public static String prettyInt(int n, int width) {
    return String.format("%" + width + "d", n);
}

Or if you want it filled by zeros :

public static String prettyInt(int n, int width) {
    return String.format("%0" + width + "d", n);
}

Leave a Reply