发布时间 : 星期一 文章基础Java数组练习题及答案教学内容更新完毕开始阅读20203504872458fb770bf78a6529647d2628346f
础ava数组练题及答案
基J习
精品文档
在开发的时候主方法之中的代码越少越好。 1、
将一个给定的整型数组转置输出, 例如: 源数组,1 2 3 4 5 6
转置之后的数组,6 5 4 3 2 1
public class MyDemo { public static void main(String args[]){ int [] data = new int[7] ; init(data) ; // 将数组之中赋值 print(data) ; System.out.println() ; reverse(data) ; print(data) ; } public static void reverse(int temp[]){ int center = temp.length / 2 ; // 求出中心点 int head = 0 ; // 表示从前开始计算脚标 int tail = temp.length - 1 ; // 表示从后开始计算脚标 for(int x = 0 ; x
1、 2、
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ; int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5} ;
确定出不为0的个数,这样可以开辟新数组;
从旧的数组之中,取出内容,并将其赋给新开辟的数组;
要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为:
思路:生活中的问题解决 = 程序中的解决;
public class MyDemo { public static void main(String args[]){ int oldArr [] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ; int newArr [] = new int[count(oldArr)] ; // 新数组 fun(oldArr,newArr) ; print(newArr) ; } public static void fun(int src[],int data[]){ int foot = 0 ; // 控制新数组的脚标,data for(int x = 0 ; x < src.length; x++){ if(src[x] != 0){ data[foot++] = src[x] ; } } } public static int count(int temp[]){ int num = 0 ; 收集于网络,如有侵权请联系管理员删除
精品文档
} 3、
for(int x = 0 ; x < temp.length; x++){ if(temp[x] != 0){ num ++ ; // 统计个数 } } return num ; } public static void print(int temp[]){ for(int x = 0 ; x< temp.length ; x++){ System.out.print(temp[x] + \、\ } } 现在给出两个数组:
· 数组A:“1,7,9,11,13,15,17,19:; · 数组b:“2,4,6,8,10”
两个数组合并为数组c,按升序排列。
public class MyDemo { public static void main(String args[]){ int data1 [] = new int[] {1,7,9,11,13,17,19} ; int data2 [] = new int[] {2,4,6,8,10} ; int newArr [] = concat(data1,data2) ; java.util.Arrays.sort(newArr) ; print(newArr) ; } public static int[] concat(int src1[],int src2[]){ int len = src1.length + src2.length ; // 新数组的大小 int arr[] = new int[len] ; // 新数组 System.arraycopy(src1,0,arr,0,src1.length) ; // 拷贝第一个数组 System.arraycopy(src2,0,arr,src1.length,src2.length) ; // 拷贝第二个数组 return arr ; } public static void print(int temp[]){ for(int x = 0 ; x< temp.length ; x++){ System.out.print(temp[x] + \、\ } } } 主要的目的是熟悉这两个操作的方法,数组扩大,必须要将原始数组的内容拷贝进去。
收集于网络,如有侵权请联系管理员删除