【问题标题】:What logic needs to be changed to get the star pattern需要改变什么逻辑才能得到星形图案
【发布时间】:2014-10-23 19:11:56
【问题描述】:
class Starr {
    public static void main(String[] args) {
        int res;
        for(int i=1;i<=5;i++) {
            for(int j=1;j<=5;j++) {
                res=i+j;
                if(res>=6) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();   
        }
    }
}

输出:

    *
   **
  ***
 ****
*****

预期:

        *
      * *
    * * *
  * * * *
* * * * * 

为了获得上述预期结果,我进行了以下更改,

  {
    System.out.print(" *"); /* Added a space before '*' */
  }
  else
  {
    System.out.print("  "); /* Added 2 spaces */
  }

我想知道这个预期结果是否可以在我不必更改打印语句的另一个逻辑中实现。我所做的任何改变都是正确的方法?

【问题讨论】:

  • 考虑到星号之间的间距在某种程度上受 println 语句的控制......我不确定你到底在问什么。
  • 您为什么要采用其他方式?该解决方案是最简单的并且效果很好。

标签: java ascii-art


【解决方案1】:

您无法在不打印任何内容的情况下在星之间打印空格,尽管您可以在不使用空格的情况下实现所需的输出。这可以通过 System.out.format() 或 System.out.printf() 来完成。 format 和 printf 在实践中实际上是一回事。特别适合你:

System.out.printf("%2s", "*");

这意味着这个输出应该打印两个字符,其中第一个应该是'*'。其余的将是空格。

【讨论】:

    【解决方案2】:
    public class StarPattern {
        public static void main(String[] args) {
            // This loop print the number of * rows
            for (int i = 5; i >= 1; i--) {
                // This prints the empty space instead of *
                for (int j = 1; j < i; j++) {
                    System.out.print(" ");
                }
                // Print the * in the desired position
                for (int k = 5; k >= i; k--) {
                    System.out.print("*");
                }
                // Move the caret to the next line
                System.out.println();
            }
        }
    }
    

    输出:

        *
       **
      ***
     ****
    *****
    

    【讨论】:

    • 对你的代码做一点解释,以便其他用户更容易理解
    【解决方案3】:

    检查此代码,它有效!

    int res;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            res = i + j;
            String sp = (j != 1) ? " " : "";
            if (res >= 6) {
                System.out.print(sp + "*");
            } else {
                System.out.print(sp + " ");
            }
        }
        System.out.println();
    }
    

    输出:

            *
          * *
        * * *
      * * * *
    * * * * *
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多