Home > Back-end >  Java from entry to the master problem: use a for loop to print a diamond.
Java from entry to the master problem: use a for loop to print a diamond.

Time:04-01

Only two for loop to print out the diamond pattern

The code is as follows:
Public static void main (String [] args) {
Int gs=1;//initialize each row number at the beginning of the cycle of characters to print every time plus 2, this assignment 1
Int lines=17;//set the height of the diamond (print graphics on the number of rows and columns), setting value should be an odd number of
for(int i=1; i<=lines; I++) {//in order to conduct unit do cycle
Gs gs +=((i<=(lines/2 + 1))? 2: - 2);//calculate the line (I) need to print the number of characters
//if the current line less than or equal to the diamond half height (rows or columns) + 1, so need to print the number of characters + 2
//if the current line than half the height of diamond + 1, then the number of characters printed - 2
//do before + 2 operation maximum print characters in length, do - 2 after operation
For (int j=1; j<=lines; J++) {//to a unit cycle

If (j> (lines - gs)/2 & amp; & j<((lines - gs)/gs + 2 + 1)) {//judge the location shows the characters or Spaces (character shows the coordinates of the range),
//"(lines - gs)/2" is the bank to print the last one space character of the coordinates of the
//"(lines - gs)/gs + 2 + 1" is the bank to print behind the characters of the first space coordinates of the
System. The out. Print (" O ");//display character O
} else {
System. The out. Print (" ");//if not character display shows the coordinates of space
}
}

System.out.println();
}


}
  • Related