0

I'm trying to format my output with System.out.printf(); function in java .
the output format is like this :

In each line of output there should be two columns: The first column contains the String and is left justified using exactly characters. The second column contains the integer, expressed in exactly digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
================================
java               100
cpp                065
python           050
================================

1 Answer 1

1

Use String's format to format strings the way "sprintf" does in C.

From that reference, adapting to your need:

  • Padding left with zeros:

    String.format("|%03d|", 93); // prints: |093|
    
  • String of spefiied length (involves max and min)

    String.format("|%-15.15s|", "Hello World"); |Hello World   |
    

    You want left justified so "-N" instead of N for first value

Java 8's official format reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-

And format string documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

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

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.