Java 格式化整行代码

huangapple go评论67阅读模式
英文:

Java Format A entire Line

问题

你好,我尝试使用Java的:

System.out.printf方法,但它没有起作用。

我正在尝试创建这样的菜单:年龄4个空格 地点4个空格 价格

我尝试了类似这样的做法 System.out.printf("%4s 年龄 地点 价格");

我希望将所有内容都格式化在一行上!

这是我想要的效果:

年龄 (四个空格) 地点 (再加4个空格) 价格

英文:

Hello I tried using the java:

System.out.printf method but it is not working.

I am trying to create a menu like this: Age 4 spaces Location 4 spaces Price

I tried doing something like this System.out.printf("%4s Age Location Price");

I would like to format everything on one line!

This is what I want:

Age (Four spaces between) Location (Another 4 spaces inbetween) Price

答案1

得分: 1

System.out.printf("%-20s %-20s %-20s", "年龄", "位置", "价格");
这将在您想要打印的每个单词之间打印空格。只需用您想要的空格数量替换我的示例即可。

英文:

>example
System.out.printf("%-20s %-20s %-20s", "Age", "Location", "Price");
This should print spaces between each word you want to print. Just replace my example with the amount of spaces you want.

答案2

得分: 0

这是我想要的内容:

年龄(四个空格)地点(另外4个空格)价格

那就简单点吧。只需使用 printprintln

System.out.println("年龄    地点    价格");

就这样。在字符串的适当位置插入所需的空格,并且不需要进行任何进一步的格式化。(使用 println 会在文本后面换行,这可能是您在这里所需的。)

如果您想要(或需要)使用 printf 等方法,那么我强烈建议您阅读方法的 javadocs 以及 Formatter 类的javadoc。后者描述了这种类型的 Java 格式化是如何工作的。通过仔细阅读,您可以了解它能做什么,以及它的局限性是什么。

英文:

> This is what I want:
>
> Age (Four spaces between) Location (Another 4 spaces inbetween) Price

Well keep it simple then. Just use print or println:

System.out.println("Age    Location    Price");

That's it. Put required spaces into the string at the appropriate point and print it without any further formatting. (Using println gives you want a newline following the text, which is probably what you need here.)

Now, you could use PrintWriter.printf, PrintWriter.format or String.format in this. You might do that if you want to express the spacing in terms of column widths. You might do it if the headings were variable sized. Or other reasons. But for this problem ... as you have described it to us ... formatting adds little value.

If you want (or need) to use to use printf etcetera then I strongly recommend that you read the method javadocs AND the javadoc for the Formatter class. The latter describes how this kind of Java formatting works. By reading it carefully you can understand what it is capable of, and what its limitations are.

huangapple
  • 本文由 发表于 2020年8月29日 09:40:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63642652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定