using printf for multiple formats

◇◆丶佛笑我妖孽 提交于 2019-12-14 02:33:24

问题


I have a question on how to use printf for multiple formats. I want something like this, where everything inside printf is spaced out evenly:

i     i     i     i     i

and this is how I used printf:

// display headers
    System.out.printf("", "%15s", "%15s", "%15s", "%15s", "Car Type", 
            "Starting Miles", "Ending Miles", "Distance/Gallon", 
            "Gallons/Distance", "Miles/Gallon");

when I executed my program, the above wouldn't show up at all, I just go this:

run:
Gas & Mileage Calculations

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
BUILD SUCCESSFUL (total time: 0 seconds)

回答1:


Just concatenate the formats:

System.out.printf("%15s%15s%15s%15s", "header 1", "header 2", ...);



回答2:


The way you use printf() is wrong.

It's first parameter is String format, which will be the formatting string, which implements all further arguments.

Example:

String name = "Chris";
int age = 25;
System.out.printf("%s = %d", name, age);

This will print out "Chris = 25", because %s is converted into the variable name and %d into variable age. Check the API docs for more information.



来源:https://stackoverflow.com/questions/20253762/using-printf-for-multiple-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!