- class ZhuanFen
- {
- public static void main(String[] args)
- {
- print();
- }
- /*
- * 1.将该数组由小到大进行排列,数组中的素数全部赋值为零,并 按阶梯状输出。
- 数组: 2 5 9 10 48 95 154 31 59 69
- * */
- public static boolean suShu(int i)//定义一个判断是否为素数的方法。
- {
- int count = 0;
- if (i == 1)
- return false;
- for(int x=1;x<=i;x++)
- {
- if((i%x)==0)
- count++;
- }
- if(count>2)
- return false;
- else
- return true;
- }
- public static void print()
- {
- int []i = {2,5,9,10,48,95,154,31,59,69};//来个int数组存需要处理的数
- System.out.print("数组改变前");
- for(int x=0;x<i.length-1;x++)
- {
- System.out.print(i[x]+" ");
- }
- System.out.println(i[i.length-1]);
- int []arr = new int[i.length];//来个新数组存素数变0后的数组。
- for(int x=0;x<i.length;x++)//遍历数组并打印。
- {
- if(suShu(i[x]))//调用suShu方法判断原数组的数是否为素数
- arr[x] = 0;
- else
- arr[x]=i[x];
- }
- System.out.print("数组改变后");
- for(int x=0;x<arr.length-1;x++)
- {
- System.out.print(arr[x]+" ");
- }
- System.out.println(arr[arr.length-1]);
- for(int x=0;x<arr.length;x++)
- {
- for(int y=0;y<=x;y++)
- {
- if(x==y)//为了打印阶梯型。
- System.out.println(arr[x]);
- else
- System.out.print(" ");
- }
- }
- }
- }
复制代码
_______________________________________________________________________________________________________________________________________________________________
- <P>class ZhuanFen1
- {
- public static void main(String args[])
- {
- int N =4;
- yanghui(N);
- }
- /*
- * 2.手动输入一个自然数N,反向打印N行杨辉三角。
- * */
- public static void yanghui( int N)
- {
- int a[][] = new int[N+1][];//定义一个二维数组。
- for(int i=0;i<=N;i++)//初始化二维数组
- {
- a[i] = new int[i+1];
- }
- for (int i = 0; i <= N; i++)//循环行数
- {
- for (int j = 0; j <= a[i].length - 1; j++) //循环列数
- {
- if (i == 0 || j == 0 || j == a[i].length - 1)
- a[i][j] = 1;//将两侧元素设为1
- else//元素值为其正上方元素与左上角元素之和
- a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
- }
- }
- for (int i=a.length-1-1;i>=0;i--)
- {
- for(int x =i+1;x<N;x++)
- System.out.print(" ");
- for (int j = 0; j <=a[i].length - 1; j++)
- System.out.print(a[i][j] + " ");
- System.out.println();//换行
- }
- }
- }</P>
- <P> </P>
复制代码
|