Home > Java > Javagetting Started > How to print out a diamond pattern using java

How to print out a diamond pattern using java

王林
Release: 2020-02-24 17:38:31
forward
5847 people have browsed it

How to print out a diamond pattern using java

首先看图:

How to print out a diamond pattern using java

第一步:首先对图像进行解析

想要打印该图形必须要进行多层循环嵌套,分两个部分进行打印。

第一部分为上半部分前四行,他们是递增的关系,后半部分后三行为递减关系,由此可以得出我们需要写两个打的循环。并且由于“*”位置的关系,我们必须带入空格同时打印。所以每个部分需要两个循环控制,即两个大循环每个里面嵌套两个小循环总计四个循环。

(相关教程推荐:java入门教程

第二部:对数字进行分析

在分析之前,我们必须明白外层循环控制行数,内层循环控制列数,因此我们需要分析他的行和列。

示例代码如下:

class ForForTest {
    public static void main(String[] args) {
        
/*
输出如下图形:    行数i:    空格数j:    “*”数目z:
     *             1         3           1
    ***            2         2           3
   *****           3         1           5
  *******          4         0           7
   *****           1         1           5      6
    ***            2         2           3      5
     *             3         3           1      4
 */
        for (int i = 1;i <= 4;i++){
            for (int j = 1;j <= 4 - i;j++) {
                System.out.print(" ");
            }
            for (int z = 1;z <= i*2-1;z++){
                System.out.print("*");
            }
            System.out.println();
        }
        for (int i = 1;i <= 3;i++){
            for (int j = 1;j <= i;j++){
                System.out.print(" ");
            }
            int y = 3;
            for (int z = 5;z >= 2*i-1;z--){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Copy after login

更多编程相关内容,请关注php中文网编程入门栏目。

The above is the detailed content of How to print out a diamond pattern using java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template