gpt4 book ai didi

java - 如何打印正数和 + 之前有空格的格式化字符串

转载 作者:行者123 更新时间:2023-12-01 23:39:42 25 4
gpt4 key购买 nike

我可以做到这一点:

public class first{
public static void main (String[] args){
String message = String.format("%s, next year you'll be % +d", "Michael", 37);
System.out.printf(message);
}
}

不工作:我收到运行时错误:

Exception in thread "main" java.util.IllegalFormatFlagsException: Flags = '+ '
at java.util.Formatter$FormatSpecifier.checkNumeric(Unknown Source)
at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at first.main(first.java:3)

嗯,我只能使用空格符号或+。然后它就可以工作了。但如何将两者结合起来呢?

最佳答案

使用 String.format("%s, 明年你将是 +%d", "Michael", 37);

这将打印,Michael,明年你将+37

提示一下,大多数人倾向于将他们的类文件大写,即 First 而不是您的名字 first。当然,如果您独自工作,您可以随意命名任何您想要的名称。但是,如果您开始与团队合作,那么您应该尝试调整自己的格式。

编辑:有人评论说你想要一个空格,所以只需输入一个空格即可,+ %d

关于java - 如何打印正数和 + 之前有空格的格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153279/

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