首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

用java语言编写一个打印出钻石形状的图形的程序解决方案

2011-12-28 
用java语言编写一个打印出钻石形状的图形的程序求解:用java语言编写一个打印出钻石形状的图形的程序,要求

用java语言编写一个打印出钻石形状的图形的程序
求解:用java语言编写一个打印出钻石形状的图形的程序,要求使用嵌套
图形如下:
                                *
                              ***
                            *****
                          *******
                            *****
                              ***
                                *


[解决办法]
public class Print
{
public static void main(String[] args)
{
for(int i=0;i <4;i++)
{
for(int j=0;j <7;j++)
{
if(j> =3-i&&j <=3+i)
{
System.out.print( "* ");
}

else
{
System.out.print( " ");
}

}
System.out.println( " ");
}


for(int i=2;i> =0;i--)
{
for(int j=0;j <7;j++)
{
if(j> =3-i&&j <=3+i)
{
System.out.print( "* ");
}

else
{
System.out.print( " ");
}

}
System.out.println( " ");
}
}
}
[解决办法]
class test{
public static void main(String[] args){
int k=0;
for (int i=0;i <7;i++)
{
for(int j=0;j <7;j++)
{
if(i <4)
{
if ((j> =3-i)&&(j <=i+3))
System.out.print( "* ");
else
System.out.print( " ");
}
else
{
k=7-i;
if ((j> =4-k)&&(j <=k+2))
System.out.print( "* ");
else
System.out.print( " ");
}
}
System.out.println( " ");
}
}
}
[解决办法]
看了大家都写2个循环的
我不写循环 写了个函数递归调用的,并可以从命令行输入最大行的参数,测试通过
我想LZ要的是我这种吧

class TestStar{
static int count=1;
static int i=1;
public static void output(int n){
if(count <=2*i-1){
System.out.print( "* ");
count++;
output(n);
}else if(i <n){
System.out.println( " ");
count=1;
i++;
output(n);
}else if(i> 0){
System.out.println( " ");
count=1;
i--;
n--;
output(n);
}
}

public static void main(String[] args){
try{
int n=Integer.parseInt(args[0]);
TestStar.output(n);
}catch(Exception e){
System.out.println( "请输入参数! ");
}
}
}
[解决办法]
楼上的,楼主的图形应该是一个菱形,因为CSDN不支持缩进才显示成了三角形。我写的:



public class Diamond {

public static void print(int size, char ch) {
for (int i=0, spaces=size/2, chars=1, j; i <size; i++) {
for (j=0; j <spaces; j++)
System.out.print( ' ');
for (j=0; j <chars; j++)
System.out.print(ch);
System.out.println();
if (i <size/2) { spaces--; chars+=2; }
else { spaces++; chars-=2; }
}
}

public static void main(String[] args) {
Diamond.print(9, '* ');
}

}

[解决办法]
用绝对值就能很好求出来了:
public class Test
{

public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
for(int i=1;i <=x;i++)
{
for(int j=1;j <=Math.abs(x/2+1-i);j++)
{
System.out.print( " ");
}
for(int j=1;j <=x-2*Math.abs(x/2+1-i);j++)
{
System.out.print( "* ");
}
for(int j=1;j <=Math.abs(x/2+1-i);j++)
{
System.out.print( " ");
}
System.out.println();
}
}

}

热点排行