search
HomeJavaJavagetting StartedHow to print out a diamond pattern using java

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

更多编程相关内容,请关注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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.