gpt4 book ai didi

java - 格式化包含许多字符串和整数的长 system.out.print

转载 作者:行者123 更新时间:2023-12-01 07:03:21 26 4
gpt4 key购买 nike

假设您有以下内容:

String cake = "whatever";
int cakeNumber = 509;
String whyNot = "another string";
double number = 1;

system.out.println("I like "+ cake +" and I eat " + cakeNumber + " blah blah prolonging this string because " + whyNot + " and so on " + number + ".");

所以,这没有多大意义,也没有必要,因为这只是一个例子。我的问题是,给定多个字符串和变量,它们之间有一个“加号”,它看起来像一团糟。没有办法格式化这个 println 或者通过减少加号的数量来稍微整理一下吗?

最佳答案

java.lang.StringBuilder

System.out.println(new StringBuilder("I like")
.append(cake)
.append(" and I eat ")
.append(cakeNumber)
.append(" blah blah prolonging this string because ")
.append(whyNot)
.append(" and so on ")
.append(number)
.append(".")
.toString());
<小时/>

java.text.MessageFormat

System.out.println(MessageFormat.format("I like {0} and I eat {1} blah blah    prolonging this string because {2} and so on {3}.",
cake, cakeNumber, whyNot, number));

我有点喜欢静态导入,如下所示:

import static java.text.MessageFormat.format;

System.out.println(format("I like {0} and I eat {1} blah blah prolonging this string because {2} and so on {3}.",
cake, cakeNumber, whyNot, number));
<小时/>

java.util.Formatter (也称为 String.format )

System.out.printf("I like %s and I eat %d blah blah    prolonging this string because %s and so on %f.%n",
cake, cakeNumber, whyNot, number);

这里有很多语法可供选择(仅列出一些,可能还有更多):

System.out.format(...)
System.out.printf(...)
System.out.print(String.format(...)) // you will need to include the line break in the format
System.out.println(String.format(...)) // line break will be caused by println()
import static java.lang.String.format;
System.out.print(format(...))
System.out.println(format(...))
System.out.println(new Formatter().format(...))

%n 表示系统特定的换行符。这是必需的,因为 printf 不会在操作后自动插入换行符。

<小时/>

多行字符串连接

System.out.println("I like " + cake + " and I eat " +
cakeNumber + " blah blah prolonging this string because" +
whyNot + " and so on " + number + ".");

关于java - 格式化包含许多字符串和整数的长 system.out.print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com