正准备费点脑力“调试”出钻石形状的输出算法,突然想到8年前已经干过这事了。
于是在CSDN中以“钻石”为关键词检索自己的文章,Bingo!
复用自己写的代码,节约的时间用来写这段心得,多好啊!
原贴:
大小可变钻石形状(Display a diamond shape constituted by asterisks)
http://blog.csdn.net/hpdlzu80100/article/details/2268427
代码如下:
//JHTP Exercise 5.24: Diamond Printing Program
//by <a target=_blank href="mailto:pandenghuang@163.om">pandenghuang@163.om</a>
/*(Diamond Printing Program) Write an application that prints the following diamond
shape. You may use output statements that print a single asterisk (*), a single space or a single newline
character. Maximize your use of repetition (with nested for statements), and minimize the
number of output statements.*/
import java.util.Scanner;
public class DiamondTest
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int size=0;
boolean guard;
System.out.print("请输入要绘制的钻石大小(奇数):");
size=input.nextInt();
while (size%2==0||size<1){
System.out.print("输入有误,请重新输入:");
size=input.nextInt();
}
for (int i=1;i<=size;i++){
for (int j=1;j<=size;j++){
if (i<=size/2+1)
guard=(size/2+1-j<i&&size/2+1-j>=0)||(j-size/2-1<i&&j-size/2-1>=0);
else
guard=(size/2+1-j<=size-i&&size/2+1-j>=0)||(j-size/2-1<=size-i&&j-size/2-1>=0);
if (guard)
System.out.print("*");
else
System.out.print(" ");}
System.out.print("\n");
}
}
}
运行结果:
Round 1:
请输入要绘制的钻石大小(奇数):5
*
***
*****
***
*
Round 2:
请输入要绘制的钻石大小(奇数):30
输入有误,请重新输入:31
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
*******************************
*****************************
***************************
*************************
***********************
*********************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*