printf (format strings)

 avatar
unknown
java
4 days ago
2.7 kB
27
Indexable
public class printf {
    public static void main(String[] args) {

        // printf --> a method we use to format output

        // where we want to add a variable --> %
        // %[flags][width][.precision][specifier-character]

        //String name = "William";
        //char letter = 'W';
        //int age = 25;
        //double height = 100.5;
        //boolean inEducation = true;


        // Specifier-character + .precision

        // s for String
        // Use backwards slash + n which is line break
        // comma to separate variables
        //System.out.printf("Hello %s!\n", name);

        // c for unicode chars
        //System.out.printf("First letter of your name: %c\n", letter);

        // d for int - represents whole number as double
        //System.out.printf("You are %d years old.\n",age);

        /* f for double - represents a floating point number
         inserting a number before f allows to limit up to a certain point (after decimal)
         known as [.precision] in this case 1 decimal point (rounding)
         */
        //System.out.printf("Your height: %.1fcm\n", height);

        // b for boolean
        //System.out.printf("Currently in education?: %b\n", inEducation);

        // You can combine them together but arguments must be last
        // ("format string", argument1, argument2 ,etc...)
        /* System.out.printf(
                "Your name is %s which begins with a %c. You are %d years old! Your height is %.1fcm, " +
                "and are you currently in education? %b" , name, letter, age, height, inEducation);
        */

        // [flags]
        // placed after %
        // + -->  output a plus
        // , --> comma grouping for thousands
        // ( --> any negative numbers are enclosed in ()
        // space --> displays a minus if negative, space if positive
        /*
        double number = 25.25;
        double number2 = 46.50;
        double number3 = -50.30;
        System.out.printf("% .1f\n", number);
        System.out.printf("% .1f\n", number2);
        System.out.printf("% .1f\n", number3);
        */

        // [width]
        // placed after %
        // 0(X) --> zero padding replacing empty slots
        // number (%3) --> padding to the right --> any empty slots turns into a space
        // minus number (%-3) --> padding to the left --> opposite of to the right
        /*
        int id = 1;
        int id2 = 55;
        int id3 = 242;
        int id4 = 2020;

        System.out.printf("%04d\n", id);
        System.out.printf("%-4d\n", id4);
        */


    }
}
Editor is loading...
Leave a Comment