简体   繁体   中英

Java String.format() syntax

I'm trying to print the following output on the screen.

     #
    ##
   ###
  ####
 #####
######

This is my code,

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int num = Integer.parseInt(sc.nextLine());

        for(int i= 1; i <= num; i++){
            String spc = String.format("%" +  (num - i) + "s", " ");
            String hash = String.format("%" + i + "#", "#");
            System.out.println(spc+hash);
        }
    }

I get the following error,

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = #
    at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)
    at java.util.Formatter$FormatSpecifier.printString(Formatter.java:2882)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2763)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.util.Formatter.format(Formatter.java:2455)
    at java.lang.String.format(String.java:2940)
    at Solution.main(Solution.java:13)

I can understand my String.format has not been done right, but the docs are confusing on printing the character # Any help appreciated.

You could try like this:

for (int i = 1; i <= num; i++) {
    String spc = (i == num) ? "" : String.format("%" + (num - i) + "s", " ");
    String hash = String.format("%" + i + "s", "#").replace(' ', '#');
    System.out.println(spc + hash);
}

Output:

     #
    ##
   ###
  ####
 #####
######

I guess you wanted to write:

       String hash = String.format("%" + i + "s", "#");

Reading the error message helped me in finding this error, though you didn't marked where line 13 is.

Try this

for(int i= 1; i <= num; i++)
        {
            if((num-i)>0)
            {
                String spc = String.format("%" +  (num - i) + "S", " ");
                String hash = String.format("%" + i + "s", "#");
                System.out.println(spc+hash);
            }
        }

I came across the same output. Here is one solution. Just in case someone stumbles again.

Instead of creating # and spaces separately, We can define width to the format method. Refer Java String Format Examples

String hash = "";
for (int i = 1; i <=n; i++) {
     hash+="#";
     System.out.println(String.format("%"+n+"s",hash));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM