如何使用嵌套循环打印出X.

i_u*_*net 0 java methods char shapes nested-loops

我已经搜索过这个问题的简单解决方案.

我有一个叫做的方法

printCross(int size,char display)
Run Code Online (Sandbox Code Playgroud)

它接受一个大小并打印一个X,其中包含它接收的高度和宽度的char变量.

调用方法printShape(int maxSize, char display)接受形状的最大大小并进入循环,向printCross方法发送2的倍数,直到达到最大值.

这是我的代码,但它没有给我预期的结果.

public static void drawShape(char display, int maxSize)
  {
    int currentSize = 2; //start at 2 and increase in multiples of 2 till maxSize

    while(currentSize<=maxSize)
    {
      printCross(currentSize,display);
      currentSize = currentSize + 2;//increment by multiples of 2
    }
  }

public static void printCross(int size, char display)
{
for (int row = 0; row<size; row++)  
        {  
            for (int col=0; col<size; col++)  
            {  
                if (row == col)  
                  System.out.print(display);  
                if (row == 1 && col == 5)  
                  System.out.print(display);  
                if (row == 2 && col == 4)  
                 System.out.print(display);  
                if ( row == 4 && col == 2)  
                 System.out.print(display);  
                if (row == 5 && col == 1)  
                 System.out.print(display);  
                else  
                  System.out.print(" ");   

            }
            System.out.println(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

是因为我把数字硬编码到循环中吗?我做了很多数学计算,但不幸的是,只有这样才能达到我想要的输出.

If the printCross() method received a size of 5 for instance, the output should be like this:
x   x
 x x
  x
 x x
x   x
Run Code Online (Sandbox Code Playgroud)

请我花上几周时间,似乎无处可去.谢谢

Chr*_*ian 6

您要做的第一件事是找到索引之间的关系.假设您有长度的方阵size(size = 5在示例中):

  0 1 2 3 4
0 x       x
1   x   x
2     x
3   x   x
4 x       x
Run Code Online (Sandbox Code Playgroud)

您可以注意到的是,在from的对角线(0,0)(4,4),索引是相同的(在代码中这意味着row == col).

此外,您还可以看到,在从对角线(0,4)(4,0)指数总是总结到4,这是size - 1(在代码中,这是row + col == size - 1).

因此,在代码中,您将循环遍历行,然后遍历列(嵌套循环).在每次迭代时,您必须检查是否满足上述条件.逻辑OR(||)运算符用于避免使用两个if语句.

码:

public static void printCross(int size, char display)
{
    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            if (row == col || row + col == size - 1) {
                System.out.print(display);
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出: (size = 5, display = 'x')

x   x
 x x 
  x  
 x x 
x   x
Run Code Online (Sandbox Code Playgroud)