黑马程序员技术交流社区
标题:
如何用for循环和数组写一个正三角形
[打印本页]
作者:
chenwt2015
时间:
2015-10-1 17:07
标题:
如何用for循环和数组写一个正三角形
import java.util.Scanner;
class Trigon
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num = 1;
for (int i = 1; i <= 6;i++ )
{
for (int j = 1;j <= i ;j++ )
{
System.out.print(num+"\t");
num++;
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.println("请输入正三角形的边长");
int size = sc.nextInt();
String[][] arr1 = new String[size][];
for (int i = 0; i < size;i++ )
{
arr1[i]=new String[i+1];
for (int j = 0;j <= i ;j++ )
{
if (i==size-1)
{
arr1[i][j]="*";
}else if(j==0 )
{
arr1[i][j]="*";
arr1[i][j]="*";
}else
{
arr1[i][j]=" ";
}
}
}
String[][] arr = new String[size-1][];
for (int i = 0; i < size-1;i++ )
{
arr[i]=new String[i+1];
for (int j = 0;j <= i ;j++ )
{
if (i==size-2)
{
arr[i][j]="*";
}else if(j==i)
{
arr[i][j]="*";
}else
{
arr[i][j]=" ";
}
}
}
for (int i=0;i<size ;i++ )
{
for (int j=size-1;j>=i ;j-- )
{
System.out.print(" ");
}
for (int j=0;j<=i ;j++ )
{
System.out.print(arr1[i][j]);
}
for (int j=1;j<=i ;j++ )
{
System.out.print(arr[i-1][j-1]);
}
/*for (int j=5;j>=0 ;j-- )
{
System.out.print(" ");
}*/
System.out.println();
}
System.out.println("请输入一个数");
int size2=sc.nextInt();
int temp1=size;
int temp2=size;
int size3=2*size2+1;
String[][] arr2=new String[size2][size3];
for (int i=0;i<size2 ;i++ )
{
for (int j=0;j<size3 ;j++ )
{
arr2[i][j]=" ";
}
}
for (int i=0;i<size2 ;i++ )
{
if(i!=size2-1)
{
arr2[i][temp1]="*";
arr2[i][temp2]="*";
temp2++;
temp1--;
}else
{
for (int j=0;j<size2 ;j++ )
{
arr2[i][temp1+j]="*";
arr2[i][temp2-j]="*";
}
}
}
for (int i=0;i<size2 ;i++ )
{
for (int j=0;j<size3 ;j++ )
{
System.out.print(arr2[i][j]);
}
System.out.println();
}
}
}
作者:
向阳啊
时间:
2015-10-1 17:45
学习了..............
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2