一、基本菱形
package regexTest;
public class Test8
{
public static void main(String[] args)
{
int length = 32;
int j = length/2;
for(int i = 0; i < 10; i++)
{
for(int k = j; k > 0; k--)
{
System.out.print(" ");
}
System.out.print("*");
if(length - 1 - 2*j > 0)
{
for(int l = 0; l < length - 1 - 2*j; l++)
{
System.out.print(" ");
}
System.out.print("*");
}
for(int k = j; k > 0; k--)
{
System.out.print(" ");
}
System.out.println("");
j--;
}
for(int i = 0; i < 11; i++)
{
for(int k = j; k > 0; k--)
{
System.out.print(" ");
}
System.out.print("*");
if(length - 1 - 2*j > 0)
{
for(int l = 0; l < length - 1 - 2*j; l++)
{
System.out.print(" ");
}
System.out.print("*");
}
for(int k = j; k > 0; k--)
{
System.out.print(" ");
}
System.out.println("");
j++;
}
}
}
二、利用数学中的线性代数编写菱形:
大家都学过线性代数吧,计算机和数学是分不开的,利用数学知识很简单的哦。
贡献我的代码,仅供参考。-- 编程思想才是精髓
package csdn;
/**
* 根据线性代数方式生成菱形
* Y
* ^
* *
* *
* *H
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* ******************************************》X
* -W* 0* * W
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* *-H
* *
* *
*
* 如图,坐标系中四条直线围成的区域为菱形区域,即满足如下条件(线性代数都学过吧):
* X/W + Y/H <= 1.0
* X/W + Y/H >= -1.0
* X/W - Y/H >= -1.0
* X/W + Y/H <= 1.0
*
* @author : gaowei
* @time : 7:07:28 PM
* @email : com.gaowei@msn.com
* @description :
*/
public class Diamond
{
/**
* 根据菱形的宽和高化菱形
* draw
* @param W
* @param H
* 7:06:55 PM
*/
public void draw( int W, int H )
{
for (double Y = H; Y >= -H; Y--) {
for (double X = -W; X <= W; X++) {
if(X/W + Y/H <= 1.0
&& X/W + Y/H >= -1.0
&& X/W - Y/H >= -1.0
&& X/W - Y/H <= 1.0 ){
System.out.print( '*' );
}else {
System.out.print( ' ' );
}
}
System.out.println();
}
}
public static void main( String[] args )
{
Diamond diamond = new Diamond();
diamond.draw( 15 , 10 );
}
}
三、精简版菱形
n为菱形边长
static void output(int n)
{
for (int i = -n; i <= n; ++i)
{
for (int j = -n; j <= n; ++j)
System.out.print(Math.Abs(j) == n - Math.Abs(i) ? "*" : " ");
System.out.println();
}
}
#阿康