阅读 63

Java中关于数组练习的常见题目(附带代码和注释)

java基础数组的练习

1.将一个给定的整型数组转置输出,
例如: 源数组,1 2 3 4 5 6
转置之后的数组,6 5 4 3 2 1

public class arrayTest1 {
    public static void main(String[] args) {
        int[] a={1,2,3,4,5,6};
        int m=a.length;
        int temp;
        for (int i = 0; i <m/2; i++) {
           temp=a[i];
           a[i]=a[m-i-1];
           a[m-i-1]=temp;
        }
        for (int i = 0; i < m; i++) {
            System.out.print(a[i]+" ");
        }
    }
}
复制代码

2.现在有如下的一个数组:
int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;
要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为:
int[] newArr = {1,3,4,5,6,6,5,4,7,6,7,5} ;

public class arrayTest2 {
    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 count=0;
        for (int i = 0; i <oldArr.length ; i++) {
            if(oldArr[i]!=0){
                count++;
            }
        }

        int[] newArr=new int[count];
        for (int i = 0,j=0; i <oldArr.length ; i++) {
            if(oldArr[i]!=0)
            {
                newArr[j]=oldArr[i];
                j++;
            }
        }
        System.out.print("新数组为:");
        for (int i = 0; i < count; i++) {
            System.out.print(newArr[i]+" ");
        }
    }
}
复制代码

3.两个整数数组 ,一个数组长5,一个数组长10, 中间的数都是随机的整数1-100之间,数组自己内部的元素不允许重复,取交集打印

	public static void main(String[] args) {
		int[] a = new int[5];
		for (int i = 0; i < a.length; i++) {
			a[i] = (int) (Math.random() * 20 + 1);
			// 如果数组的 值和前面的重复了,那么我们需要重新赋值
			for (int j = 0; j < i; j++) {
				if (a[j] == a[i]) {
					i--;
					break;
				}
			}
		}
		int[] b = new int[10];
		for (int i = 0; i < b.length; i++) {
			b[i] = (int) (Math.random() * 20 + 1);
			// 如果数组的 值和前面的重复了,那么我们需要重新赋值
			for (int j = 0; j < i; j++) {
				if (b[j] == b[i]) {
					i--;
					break;
				}
			}
		}
		System.out.println(Arrays.toString(a) + " " + Arrays.toString(b));

		// 两层for循环
		System.out.println("交集为:");
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < b.length; j++) {
				if (a[i] == b[j]) {
					System.out.print(a[i] + "\t");
				}
			}
		}

	}
复制代码

4.现在给出两个数组:
数组a:“1,7,9,11,13,15,17,19”
数组b:“2,4,6,8,10”
两个数组合并为数组c

public class arrayTest3 {
    public static void main(String[] args) {
        int[] a = {1, 7, 9, 11, 13, 15, 17, 19};
        int[] b = {2, 4, 6, 8, 10};
        int m = a.length + b.length;
        int j = 0,temp;
        int[] c = new int[m];
        for (int i = 0; i < a.length; i++) {
            c[i] = a[i];
        }
        for (int i = a.length; i < m; i++) {
            c[i] = b[j];
            j++;
        }

        for(int i=0;i<m-1;i++){
        for(int s=0;s<m-1-i;s++){
         if(c[s]>c[s+1]){
            temp=c[s];
            c[s]=c[s+1];
            c[s+1]=temp;
            }
        }
    }
        for (int i = 0; i < m; i++) {
            System.out.print(c[i] + " ");
        }
    }
}
复制代码
文章分类
Android
文章标签