简体   繁体   English

Java String.format()语法

[英]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. 我可以理解我的String.format尚未正确完成,但是文档在打印字符时令人困惑#任何帮助表示赞赏。

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. 阅读错误消息有助于我发现此错误,尽管您没有标记第13行在哪里。

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. 不必单独创建#和空格,我们可以为format方法定义宽度。 Refer Java String Format Examples 请参阅Java字符串格式示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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