需要改变什么逻辑来获得星形模式

时间:2014-10-23 19:11:57

标签: java ascii-art

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 */
  }

我想知道这个预期结果是否可以在另一个我不必更改print语句的逻辑中实现。我做了什么改变是正确的方法?

3 个答案:

答案 0 :(得分:0)

检查此代码,它有效!

    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();   
    }

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

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();
        }
    }
}
相关问题