A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 1243382506 中级黑马   /  2016-7-30 22:35  /  514 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

现有一个数组 int[] arr1={4,3,1,5,0,6,0,0,6,5,7,6,7,8,4,9,9,0,5,8};要求:(1)将此数组中值为零的项去掉,把其他值存入新数组 int[] arr2 中;(2)将新数组中值相同的项去掉,生成一个新的数组 int[] arr3;(3)遍历两个新的数组。

6 个回复

倒序浏览
public class MyArrays {
        static int count = 0;
        public static void main(String[] args) {
                //1.定义数组
                int[] arr = {4,3,1,5,0,6,0,0,6,5,7,6,7,8,4,9,9,0,5,8};
                //2.先建立一个长度和原数组相同的数组
                int[] arr2 = new int[arr.length];
                //3.遍历原数组将不重复的元素放到新数组中
                //3.1在遍历时定义临时变量,统计有效元素的个数
                for(int i = 0;i<arr.length;i++) {
                        //判断该元素在新数组中是否存在
                        if(!containsElement(arr2, arr[i])) {
                                arr2[count++] = arr[i];
                        }
                }
                //4.根据有效元素的个数定义第三个数组
                int[] arr3 = new int[count];
                //4.1将第二个数组中的元素拷贝到第三个数组中
                for(int i = 0;i<count;i++) {
                        arr3[i] = arr2[i];
                }
                //打印去重之后的数组
                //[1, 2, 3, 5, 6, 7]
                //System.out.println(Arrays.toString(arr3));
                toString(arr3);
        }
       
        public static void toString(int[] arr) {
                //[1, 2, 3, 5, 6, 7]
                for(int i = 0;i<arr.length;i++) {
                        if(i==0){
                                System.out.print("["+arr[i]+", ");
                        } else if(i==arr.length-1) {
                                System.out.println(arr[i]+"]");
                        } else {
                                System.out.print(arr[i]+", ");
                        }
                }
        }
        /*
         * 判断数组中是否存在某元素
         * 存在返回:true
         * 不存在返回:false
         */
        public static boolean containsElement(int[] arr,int num) {
               
                for(int i = 0;i<count;i++) {
                        if(arr[i]==num)
                                return true;
                }
                return false;
        }
}
回复 使用道具 举报 1 0
跪求大神指点
回复 使用道具 举报
去0太简单了  直接加一个判断是否为0 是 就加continue就行
回复 使用道具 举报
it老菜鸟 发表于 2016-7-30 22:52
public class MyArrays {
        static int count = 0;
        public static void main(String[] args) {

多谢指点
回复 使用道具 举报
it老菜鸟 发表于 2016-7-30 22:52
public class MyArrays {
        static int count = 0;
        public static void main(String[] args) {

多谢指点{:3_64:}
回复 使用道具 举报
你做出来了吗
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马