Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading