Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Print a diamond

Java Example – Print a diamond

Java Examples Java Examples

Output a diamond with a specified number of rows.

Example

public

class

Diamond

{

public

static

void

main

(

String

[

]

args

)

{

print

(

8

)

;

//

Output a diamond with 8 rows

}

public

static

void

print

(

int

size

)

{

if

(

size

%

2

==

0

)

{

size

++;

//

Calculate the diamond size

}

for

(

int

i

=

0

;

i

<
size
/
2
1

;

i

++

)

{

for

(

int

j

=

size

/

2

1

;

j

i

1

;

j

--

)

{

System

.

out

.

print

(

"

"

)

;

//

Output the blank spaces at the top-left position

}

for

(

int

j

=

0

;

j

<
2
i
1

;

j

++

)

{

System

.

out

.

print

(

"

"

)

;

//

Output the top half edge of the diamond

}

System

.

out

.

println

(

)

;

//

Newline

}

for

(

int

i

=

size

/

2

1

;

i

<

size

;

i

++

)

{

for

(

int

j

=

0

;

j

<
i
size
/
2

;

j

++

)

{

System

.

out

.

print

(

"

"

)

;

//

Output the bottom-left blank of the diamond

}

for

(

int

j

=

0

;

j

<
2
size
1
2
i

;

j

++

)

{

System

.

out

.

print

(

"

"

)

;

//

Output the bottom half edge of the diamond

}

System

.

out

.

println

(

)

;

//

Newline

}

}

}

Output result:


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

Java Examples Java Examples