简体   繁体   English

java printf需要帮助

[英]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. 单词“ Arcot”没有足够的填充,尽管单词“ 100”足够。 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 . 您必须插入\\nprintf的第一个参数的末尾添加换行符。

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. %n是字符串格式的首选表示法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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