如何使用for循环在Java中打印x模式? [英] How to print x pattern in Java using for loops?

查看:99
本文介绍了如何使用for循环在Java中打印x模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在输入为3时获得此输出:

My goal is to get this output when input is 3:

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

这是我的代码:

public static void PrintX (int number) {
 for (int i = 0; i <= (number * 2 + 1); i++)
   {
       for (int j = 0; j <= (number * 2 + 1); j++)
       {
           if (i == j) 
           {
               System.out.print("*");
           }
           else if (i + j == (number * 2 + 2))
           {
               System.out.print("*");
           }
           else
           {
               System.out.print(" ");
           }
       }
       System.out.println("");
   }
} 

当输入为3时,我的输出是这样的,我不确定为什么顶部有多余的星星.

My output when input is 3 is like this and I'm not sure why there is the extra star at the top.

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

推荐答案

在外部for循环内设置i = 1.编译并运行以下示例:

Set i = 1 inside outer for loop. Compile and run the example below:

    public class TestPrintX {
        public static void PrintX (int number) {
         for (int i = 1; i <= (number * 2 + 1); i++)
           {
               for (int j = 0; j <= (number * 2 + 1); j++)
               {
                   if (i == j) 
                   {
                       System.out.print("*");
                   }
                   else if (i + j == (number * 2 + 2))
                   {
                       System.out.print("*");
                   }
                   else
                   {
                       System.out.print(" ");
                   }
               }
               System.out.println("");
           }
        } 
        public static void main(String arg[]) {
            PrintX(3);
        } // end of main method
} // end of class

这篇关于如何使用for循环在Java中打印x模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆