简体   繁体   English

我需要 Java 金字塔代码方面的帮助

[英]I need help in java pyramid code

I need help with this我需要这方面的帮助

1****** 
12***** 
123**** 
1234*** 
12345** 
123456* 
1234567

Using 3 for loops this will be completed.使用 3 个 for 循环,这将完成。 i tried this我试过这个

public class Pattren {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int i,j,k;
        for (i = 1; i <= 7; i++)
        {
            for (j = 1; j <= i; ++j)
            {

                    System.out.print((j)+("\n"));

                for (k = 7 - i; k >= 1; k--)
                {
                    System.out.print("* ");

                }
            }
        }           
    }
}

But there is some logical problem with it.但它有一些逻辑问题。 I need improvement in thos code.我需要改进这些代码。 I got this output.我得到了这个输出。

1
* * * * * * 1
* * * * * 2
* * * * * 1
* * * * 2
* * * * 3
* * * * 1
* * * 2
* * * 3
* * * 4
* * * 1
* * 2
* * 3
* * 4
* * 5
* * 1
* 2
* 3
* 4
* 5
* 6
* 1
2
3
4
5
6
7

An easier version would be一个更简单的版本是

    int i,j;
    for (i = 1; i <= 7; i++)
    {
        for (j = 1; j <= 7; ++j)
        {
            if (j <= i) {
                System.out.print(j);
            }
            else {
                System.out.print("*");
            }
        }
        System.out.println();
    }   

Output输出

1******
12*****
123****
1234***
12345**
123456*
1234567

Below is a solution with much fewer lines of code:下面是一个代码行更少的解决方案:

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    String s = "";
    for(int i=1; i<=7; i++){
        s += i;
        sb.append(String.format("%-7s", s).replace(" ", "*")).append("\n");
    }
    System.out.println(sb.toString());
}

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

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