打印*图案

时间:2017-06-28 08:53:19

标签: java

所以我必须通过接受n的值来打印以下模式      输入:7      输出必须是这样的:

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

代码:

public static void printPattern(int n)
{
    for(int i=1;i<=n;i++)   
    {
        for(int j=1;j<=i;j++)   
        {
            System.out.println("*");
        }
        System.out.println("\n");
    }   
    for (int a = n-1; a >= 1; a--)
    {
        for (int b = 1; b <= a; b++)
        {
            System.out.print("*");
        }
        System.out.println("\n");
    }
}

但由于某种原因,它打印出这种模式(比如说n = 8):

*


*
*
*
*
*


*
*
*
*
*
*


*
*
*
*
*
*
*


*
*
*
*
*
*
*
*


*******

******

*****

****

***

**

*

这里的错误是什么?

4 个答案:

答案 0 :(得分:2)

在第一个for循环中使用System.out.print而不是System.out.println,后者总是在末尾添加换行符,这是您尝试手动执行的操作。

要么System.out.print("\n"); OR System.out.println("");要在内循环迭代后添加换行符。

答案 1 :(得分:1)

System.out.println已在末尾添加换行符,因此System.out.println("\n")会添加两个换行符。

代码可以压缩为单个双for循环。以下例程接受一个参数,该参数定义单行上的最大“*”数:

/**
 * @param width
 *            the maximum width of the pattern.
 */
public static void print(int width) {
    for (int i = 1; i < 2 * width; ++i) {
        for (int j = 0; j < width - Math.abs(width - i); ++j)
            System.out.print("*");
        System.out.println();
    }
}

public static void main(String[] args) {
    print(4);
}

输出:

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

答案 2 :(得分:0)

首先for循环应该是这样的,

for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");

            }
            System.out.print("\n");

        }

System.out.println(); 

始终将光标移动到新行 在我们使用System.out.println("\n");的代码中,这会将光标移动到2行

答案 3 :(得分:0)

for (int i = 1; i <= n; i++) {
     for (int j = 1; j <= i; j++) {
         System.out.print("*");
     }
     System.out.println();
}
for (int a = n - 1; a >= 1; a--) {
     for (int b = 1; b <= a; b++) {
         System.out.print("*");
     }
     System.out.println();
}

println更改为print后,您不会在每个*之后转到另一行,并删除\n以不跳过2行,因为打印 ln 它已经存在

相关问题