如何在正数和+之前打印带空格的格式化字符串

时间:2013-08-09 18:27:34

标签: java

我可以这样做:

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)

好吧,我只能用空格符号或+。然后它正在工作。但是我如何将两者合并?

3 个答案:

答案 0 :(得分:3)

使用String.format("%s, next year you'll be +%d", "Michael", 37);

这将打印Michael, next year you'll be +37

只是一个提示,大多数人倾向于将他们的班级文件大写,即First而不是你的名字,first。当然,如果你一个人工作,你可以随心所欲地命名任何你想要的东西,无论你想叫什么。但是,如果你开始与团队合作,那么你应该尝试使用你的格式。

修改:有人评论说你想要一个空格,所以只需要抛出这样的空格,+ %d

答案 1 :(得分:0)

只需使用"%s, ... + %d", "str", 37

即可

答案 2 :(得分:0)

试试这个,为%

添加了转义
String message = String.format("%%s, next year you'll be %% +d", "Michael", 37);

这将解决错误,但要解决格式化尝试:

String message = String.format("%s, next year you'll be +%d", "Michael", 37);

干杯!!