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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23976995/
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-08-14 09:29:48  来源:igfitidea点击:

How to print out an X using nested loops

javamethodscharnested-loopsshapes

提问by i_use_the_internet

I have searched through to find a simple solution to this problem.

我已经搜索过以找到解决此问题的简单方法。

I have a method called

我有一个方法叫

printCross(int size,char display)

It accepts a size and prints an X with the char variable it receives of height and width of size.

它接受一个大小并用它接收的大小的高度和宽度的字符变量打印一个 X。

The calling method printShape(int maxSize, char display)accepts the maximum size of the shape and goes in a loop, sending multiples of 2 to the printCross method until it gets to the maximum.

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

Here is my code but it is not giving me the desired outcome.

这是我的代码,但它没有给我想要的结果。

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(); 
    }
}

Is it because I hardcoded the figures into the loop? I did a lot of math but unfortunately it's only this way that I have been slightly close to achieving my desired output.

是因为我将数字硬编码到循环中吗?我做了很多数学计算,但不幸的是,只有这样我才稍微接近实现我想要的输出。

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

Please I have spent weeks on this and seem to be going nowhere. Thanks

拜托,我已经花了数周时间,似乎无处可去。谢谢

采纳答案by Christian

The first thing you have to do is to find relationships between indices. Let's say you have the square matrix of length size(size = 5in the example):

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

  0 1 2 3 4
0 x       x
1   x   x
2     x
3   x   x
4 x       x

What you can notice is that in the diagonal from (0,0)to (4,4), indices are the same (in the code this means row == col).

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

Also, you can notice that in the diagonal from (0,4)to (4,0)indices always sum up to 4, which is size - 1(in the code this is row + col == size - 1).

此外,您还可以注意到,在对角线中,从(0,4)(4,0)索引的总和为4,即size - 1(在代码中为row + col == size - 1)。

So in the code, you will loop through rows and then through columns (nested loop). On each iteration you have to check if the conditions mentioned above are met. The logical OR (||) operator is used to avoid using two ifstatements.

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

Code:

代码:

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();
    }
}

Output:(size = 5, display = 'x')

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

x   x
 x x 
  x  
 x x 
x   x

回答by Nuri Tasdemir

Instead of giving a direct answer, I will give you some hints.

与其直接回答,不如给你一些提示。

First, you are right to use nested for loops.

首先,使用嵌套 for 循环是正确的。

However as you noticed, you determine when to print 'x' for the case of 5.

但是,正如您所注意到的,您决定何时为 5 的情况打印“x”。

Check that 'x' is printed if and only if row = col or row + col = size - 1

检查当且仅当 row = col 或 row + col = size - 1 时才打印 'x'

回答by Risette

for your printCross method, try this:

对于您的 printCross 方法,请尝试以下操作:

public static void printCross(int size, char display) {
    if( size <= 0 ) {
        return;
    }

    for( int row = 0; row < size; row++ ) {
        for( int col = 0; col < size; col++ ) {
            if( col == row || col == size - row - 1) {
                System.out.print(display);
            }
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

ah, I got beaten to it xD

啊,我被打败了 xD

回答by N1hk

Here's a short, ugly solution which doesn't use any whitespace strings or nested looping.

这是一个简短而丑陋的解决方案,它不使用任何空白字符串或嵌套循环。

public static void printCross(int size, char display) {
    for (int i = 1, j = size; i <= size && j > 0; i++, j--) {
        System.out.printf(
              i < j ? "%" + i + "s" + "%" + (j - i) + "s%n"
            : i > j ? "%" + j + "s" + "%" + (i - j) + "s%n"
            : "%" + i + "s%n", //intersection
            display, display
        );
    }
}

回答by vivekcs0114

Lte's try this simple code to print cross pattern.

我们试试这个简单的代码来打印十字图案。

class CrossPattern {
         public static void main(String[] args) {
          Scanner s = new Scanner(System.in);
          System.out.println("enter the number of rows=column");
          int n = s.nextInt();
          int i, j;
          s.close();
          for (i = 1; i <= n; i++) {
           for (j = 1; j <= n; j++) {
            if (j == i) {
             System.out.print("*");
            } else if (j == n - (i - 1)) {
             System.out.print("*");
            } else {
             System.out.print(" ");
            }
           }
           System.out.println();
          }
         }
        }