Java for循环制作星号矩阵

时间:2016-07-04 13:35:35

标签: java for-loop matrix nested asterisk

我目前正在尝试使用Java中的for循环创建此表单:

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

我的代码如下所示:

        for (int row = 1; row <= 10; row++) {
        for (int star = 10; star >= 1; star--) {
            if (star >= row) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

输出如下:

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

我似乎无法想象让空白在星星之前消失。我试过切换循环条件,但它只给了我相同的结果。 关于这些for循环我还没有得到什么。有人能指出我正确的方向:)

5 个答案:

答案 0 :(得分:1)

将内循环更改为标准的1到10循环。

  for (int row = 1; row <= 10; row++) {
    for (int star = 1; star <= 10; star++) {
        if (star >= row) {
            System.out.print("*");
        } else {
            System.out.print(" ");
        }
    }
    System.out.println();
}

答案 1 :(得分:1)

试试这个

int size = 10;
for (int row = 0; row < size; row++)
{
    for (int i = 0; i < row; i++)
    {
        System.out.print(" ");
    }

    for (int i = size - row; i > 0; i--)
    {
        System.out.print("*");
    }

    System.out.println();
}

答案 2 :(得分:1)

第一项工作是离开键盘并思考问题。事实证明,明星的条件是&#34;当前行&gt; =当前列&#34;。

使用

实施
for (int row = 1; row <= 10; ++row){
    for (int col = 1; col <= 10; ++col){
        System.out.print( row >= col ? "*" : " ");
    }
    System.out.println();
}

答案 3 :(得分:1)

所以我试着分析你的代码和我发现的是

你的错误:

在这里,我们看到所需的输出和输出与输出行号2不同,我找到的原因是if条件star >= row所以让我们迭代{的循环{1}}值row

2

所以if(star >= row) //when star = 10 - condition true. * will be the output if(star >= row) //when star = 9 - condition true. * will be the output if(star >= row) //when star = 8 - condition true. * will be the output 将是输出,直到*返回false,这将是此迭代的star>=row场景。
同样地,对于star = 1,条件将为真,除非row = 3值变为star。因此,问题是您在开始时打印<=2,并在打印*后出现的条件。

可能的解决方案:

基本上你需要在开始时打印*,而不是最后打印。因此,在相同条件下,您可能需要反转列的迭代方法以反转打印顺序。如果你改变循环的顺序,你就可以完成这项工作。让我们迭代 row的{​​{1}}值的循环:

2

因此,在这种情况下,if(star >= row) //when star = 1 - condition false. ` ` will be the output if(star >= row) //when star = 2 - condition true. * will be the output if(star >= row) //when star = 8 - condition true. * will be the output 将首先打印,将在稍后打印。

更新代码:

我已更新您的代码。看看*

inner for loop

希望这会有所帮助:)

答案 4 :(得分:0)

 for(int i = 0 ; i < 10 ; i++){

         for(int j = 0 ; j < 10  ; j++){

             if(j >= i){
                System.out.print("*"); 
             }else{
                 System.out.print(" ");
             }
         }
            System.out.println("");

     }