Java嵌套循环

项目描述:

编写程序以打印21行大X形状的X,如下图所示。 确保两行在“11”行相交。

这是我想要的输出:

样本输出图像

这是我到目前为止所拥有的。

public class Program168h { public static void main (String [] args) { String d= "X"; for (int a = 1; a = 1; b--) { System.out.print(" "); } System.out.print(d); for (int x = a; x < 22; x++) { System.out.print(" "); } System.out.print(d); System.out.println(); } } } 

这只产生X的前半部分,我不知道如何产生下半部分。

试试这个:

 int xSize = 21; int ySize = 21; String sign = "X"; for (int i = 0; i < xSize; ++i) { for (int j = 0; j < ySize; ++j) { if (i == j) { System.out.print(sign); } else if (i == ySize - j - 1) { System.out.print(sign); } else { System.out.print(" "); } } System.out.println(); } 

解释:第一个操作Xaxis坐标,第二个操作Yaxis。 我们的任务是覆盖对角线。 覆盖第一对角线是coordinateX == coordinateY的位置。 在代码中是if(i == j)。 这些是点(1,1),(2,2)......第二对角线是其中(x,y)=(20,1),(19,2),(18,3)的点。 ..这种情况包括第二个if(i == ySize - j - 1)。

你可以尝试:

 public class ProductX { public static void main(String[] args) { for (int i = 0; i <= 10; i++) { for (int j = 0; j < 10; j++) { System.out.print(" "); if (i == j) { System.out.print("X"); } if(j == 9-i){ System.out.print("X"); } } System.out.println();} } } 

虽然上述解决方案完美无缺,但我试图通过不使用嵌套来进行实验,并且灵魂化如下。 这将比使用嵌套时具有更高的性能,当与O(n)相比时,嵌套的复杂度为O(n2)。

  public void testXFormation() { final int countOfLines = 21; int countOfSpaceBefore = 0; int countOfSpacesAfter = countOfLines -2 ;// 2 characters boolean halfReached = false; for (int index = 0; index < countOfLines; index++) { printSpaces(countOfSpaceBefore); // print required no. of spaces System.out.print("x"); // print first x printSpaces(countOfSpacesAfter); // print required no. of spaces after x if (index != (countOfLines / 2))// Avoid printing double, in the middle System.out.print("x"); System.out.println(""); // move to next line /* Once you reach half matrix we need to reverse the logic */ if (index >= (countOfLines - 1) / 2) { halfReached = true; } /* Reversing the logic for the spaces to be printed */ if (halfReached) { countOfSpaceBefore--; countOfSpacesAfter += 2; } else { countOfSpaceBefore++; countOfSpacesAfter -= 2; } } } private void printSpaces(int count) { for (int i = 0; i < count; i++) System.out.print(" "); }