臭名昭着的三角循环...扭曲

时间:2015-10-12 23:42:00

标签: java

所以我必须输出一个带有边框的星号的直角三角形。我可以做的三角形没问题,但是边界给我带来了困难。我在循环中想到了另一个if / else,但我不知道如何表达它。我想要的结果是:

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

如果没有帮助我能得到的是:

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

这是我的代码:

public class Pattern
 {
    public static void main(String[] args)
    {
        final int WIDTH = 7;

        for (int row = 1; row <= (WIDTH); row++)
        {
            for (int col = 1; col <= (WIDTH); col++)
            {
                if (row <= col)
                {
                    System.out.print("*");
                }

                else
                {
                    System.out.print(" ");
                } 

            }
            System.out.println();
        }
        System.out.println("\n\nGoodbye!");
    }
 }

3 个答案:

答案 0 :(得分:0)

提示,边框始终位于第一个索引和最后一个索引

坚持下去:D

答案 1 :(得分:0)

试试这个:)

 public static void main(String[] args) {

    final int WIDTH = 7;

    for (int row = 1; row <= (WIDTH); row++)
    {

        for (int col = 1; col <= (WIDTH); col++)
        {
            if (col ==1){
                System.out.print("*");
            }else if (row ==WIDTH){
                System.out.print("*");
            }
            else if (row < col)
            {
                System.out.print("*");
            }

            else
            {
                System.out.print(" ");
            }

        }
        System.out.println();
    }
    System.out.println("\n\nGoodbye!");
}

答案 2 :(得分:0)

这应该有效,

public class Pattern
 {
    public static void main(String[] args)
    {
        final int WIDTH = 7;

        for (int row = 1; row < (WIDTH); row++)
        {
            System.out.print("*");

            for (int col = 1; col < (WIDTH); col++)
            {
                if (row <= col)
                {
                    System.out.print("*");
                }

                else
                {
                    System.out.print(" ");
                } 

            }

            System.out.println("");
        }

        for(int i = 1; i <= (WIDTH); i++) {

            System.out.print("*");
        }

        System.out.println("\n\nGoodbye!");
    }
 }