如何在Java中打印给定的菱形图案? [英] How to print a given diamond pattern in Java?
本文介绍了如何在Java中打印给定的菱形图案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
***********
***** *****
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
***** *****
***********
基本上,我只需要正确放置空格的想法.到目前为止,我的代码.
Basically I just need the idea to put the spaces correctly. My code so far.
public class Pyramid3 {
public static void main(String[] args) {
int i, j;
int noOfCol = 11;
for (i = 1; i <= 11; i++) {
for (j = 1; j <= noOfCol; j++) {
System.out.print("*");
}
System.out.println();
if (i == 1) {
noOfCol--;
} else if (i > 1 && i < 6) {
noOfCol = noOfCol - 2;
} else if (i > 6) {
noOfCol = noOfCol + 2;
}
}
}
}
推荐答案
这是代码,对不起,文档不好,希望对您有所帮助.
This is the code, sorry for bad documentation, hope it helps.
PS:要解决类似这样的问题,只需使用白皮书和铅笔,然后将列和索引"i"制成网格,然后找出一个关系,然后将其用作循环条件即可.
PS: to solve any problem like this, just use a white paper and a pencil then make grids of columns and the index 'i' then figure a relation, then you can use it as loop condition.
public class Test {
public static void main(String[] args) {
int n = 10;
// Top
for (int i = n; i > 0; i--) {
// Stars
for (int j = 0; j < i; j++) {
System.out.print("*");
}
// Spaces
for (int j = i; j < n; j++) {
System.out.print(" ");
}
// Stars
for (int j = i; j < n; j++) {
System.out.print(" ");
}
// Stars
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
// Bottom
for (int i = 2; i < n + 1/* Note the shift here */; i++) {
// Stars
for (int j = 0; j < i; j++) {
System.out.print("*");
}
// Spaces
for (int j = i; j < n; j++) {
System.out.print(" ");
}
// Spaces
for (int j = i; j < n; j++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
希望它会有所帮助:)
这篇关于如何在Java中打印给定的菱形图案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文