java Java中的倒直三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32260163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:54:25  来源:igfitidea点击:

Upside down right triangle in Java

javaloopsfor-loop

提问by John

I need to do this:

我需要这样做:

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

and I have this code:

我有这个代码:

for (int i=0; i<5; i++)
        {
            for (int j=5; j>i; j--)
            {    
                System.out.print("*");
            }
            System.out.println("");

which outputs this:

输出这个:

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

I cant figure out how to implement the spaces. Any help appreciated.

我不知道如何实现空间。任何帮助表示赞赏。

回答by Tunaki

You need to use two for-loops: one for the number of spaces and one for the number of *:

您需要使用两个 for 循环:一个用于空格数,另一个用于*

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < i; j++) {    
        System.out.print(" ");
    }
    for (int j = i; j < 5; j++) {    
        System.out.print("*");
    }
    System.out.println();
}

Java 8 solution:

Java 8 解决方案:

IntStream.range(0, 5).forEach(i -> {
    IntStream.range(0, i).forEach(j -> System.out.print(" "));
    IntStream.range(i, 5).forEach(j -> System.out.print("*"));
    System.out.println();
});

回答by Wander Nauta

Here's a solution with one less loop than the other answers, if you really want to wow the person who's grading your assignment:

这是一个比其他答案少一个循环的解决方案,如果你真的想让给你的作业评分的人惊叹:

for (int y = 0; y < 5; y++) {
    for (int x = 0; x < 5; x++) {
        System.out.print((x >= y) ? "*" : " ");
    }

    System.out.println();
}

回答by user3437460

Just print knumber of spaces before start of every line.

只需k在每行开始之前打印空格数。

To solve this kind of problems, it will be easy if you break it down and observe the pattern.

要解决这类问题,分解并观察模式会很容易。

*****  0 space
 ****  1 space
  ***  2 spaces
   **  3 spaces
    *  4 spaces

After taking note of this pattern, you ask yourself will you be able to print this?

记下这个图案后,你问自己你能打印这个吗?

0*****
1****
2***
3**
4*

We see that the number is similar to the start of every line. Hence we could make use of variable i. (your outer loop counter) and we have..

我们看到数字与每一行的开头相似。因此我们可以使用变量 i。(你的外循环计数器),我们有..

for (int i=0; i<5; i++){
    System.out.println(i);
    for (int j=5; j>i; j--){ 
        System.out.print("*");
    }
    System.out.println("");
}

Now, you just have to convert your numbers at the start of every line to the number of spaces and you have..

现在,您只需将每一行开头的数字转换为空格数,您就可以......

for (int i=0; i<5; i++){
    for(int k=0; k<i; k++)    //using i to control number of spaces
        System.out.println(" ");
    for (int j=5; j>i; j--){ 
        System.out.print("*");
    }
    System.out.println("");
}