简体   繁体   中英

java printf help needed

public class Format
{
    public static void main(String args[])
    {
        System.out.printf("%30s|%30s","Organization","Number of users");
        System.out.printf("%30s|%30s","Arcot","100");
    }
}

It prints:

          Organization|               Number of users                          Arcot|                           100

Why is the 2nd row out of alignment? The word "Arcot" is not given enough padding, although the word "100" is. I'm sorry, this text window applies its own formatting, it is not showing what I have pasted as the output. You may need to run the code to see the output obtained.

Try these.

System.out.println(String.format("%30s|%30s","Organization","Number of users"));
    System.out.println(String.format("%30s|%30s","Arcot","100"));
System.out.printf("%30s|%30s\n","Organization","Number of users");
System.out.printf("%30s|%30s\n","Arcot","100");

You have to insert \\n issue a newline character end of first parameter of printf .

More info about using escape character .

This works as expected:

System.out.printf("%30s|%30s%n","Organization","Number of users");
System.out.printf("%30s|%30s%n","Arcot","100");

results in

              Organization|               Number of users
                     Arcot|                           100

on my machine. You didn't add line feeds. %n is the preferred notation in format Strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM