String.format() throws FormatFlagsConversionMismatchException

后端 未结 2 771
一个人的身影
一个人的身影 2021-01-12 22:17

This code works fine in Java 1.6:

 public static String padLeft(String s, int n)
 {
     if (n <= 0)
         return s;
     int noOfSpaces = n * 2;
              


        
相关标签:
2条回答
  • 2021-01-12 22:28

    Since you are using # flag in format string, you should pass Formattable as an argument (doc).

    Any work arounds?

    Don't use # in format string?

    0 讨论(0)
  • 2021-01-12 22:42

    You asked for a workaround; just use StringBuilder:

    public static String padLeft(String s, int n) {
        if (n <= 0)
            return s;
        int noOfSpaces = n * 2;
        StringBuilder output = new StringBuilder(s.length() + noOfSpaces);
        while (noOfSpaces > 0) {
            output.append(" ");
            noOfSpaces--;
        }
        output.append(s);
        return output.toString();
    }
    
    0 讨论(0)
提交回复
热议问题