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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© dd6434541 中级黑马   /  2016-5-10 23:38  /  812 人查看  /  12 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文


/*
* 3. 在项目的根目录下有个number.txt, 文件中存放的内容为:           3
4
7
4
9
(1)将文件中所有的元素都放在list中
(2)将list中重复的元素删除
(3)将集合中的元素放入到数组中, 并按照从大到小的顺序排序后输出
将list中所有的元素用两种方式打印出来
*/
public class Test3_A {
        public static void main(String[] args) throws Exception {
                List<Integer> list = new ArrayList<>();
                // 1将文件中所有的元素都放在list中
                BufferedReader br = new BufferedReader(new FileReader("number.txt"));

                String b;
                while ((b = br.readLine()) != null) {
                        int i = Integer.parseInt(b);
                        list.add(i);
                }
                br.close();

                // 2将list中重复的元素删除
                List<Integer> newList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                        if (newList.contains(list.get(i))) {
                                list.remove(i);
                        } else {
                                newList.add(list.get(i));
                        }
                }

                // 3将集合中的元素放入到数组中, 并按照从大到小的顺序排序后输出
        int[] arr = new int[list.size()];
        /*                for (int i = 0; i < list.size(); i++) {
                        arr[i] = list.get(i);
                }
                Arrays.sort(arr);
               
                for (int i = arr.length - 1; i >= 0; i--) {
                        System.out.println(arr[i]);
                }*/
               
               
                for (int i = 0; i < arr.length; i++) {
                        for (int j = i+1; j < arr.length; j++) {
                                if( arr[i] > arr[j]) {
                                        int temp = arr[j];
                                        arr[j] = arr[i];
                                        arr[i] = temp;
                                }
                        }
                }
                // 4将list中所有的元素用两种方式打印出来
                // 1
                for (int x : list) {
                        System.out.println(x);
                }
                // 2
                Iterator<Integer> it = list.iterator();
                while (it.hasNext()) {
                        int x = it.next();
                        System.out.println(x);
                }
        }
}

评分

参与人数 1黑马币 +2 收起 理由
fengge169 + 2 赞一个!

查看全部评分

12 个回复

倒序浏览
就一个题啊?
回复 使用道具 举报
怎么就一道  总共几道? 都是那个方面的
回复 使用道具 举报
.......都好慌啊
回复 使用道具 举报
谢谢.......
回复 使用道具 举报
赞一下,支持一下。
回复 使用道具 举报
了解,但是怎么就一个题
回复 使用道具 举报
Mr.Wu 中级黑马 2016-5-11 11:41:54
8#
谢谢分享
回复 使用道具 举报
xiaogui 来自手机 中级黑马 2016-5-11 12:18:30
9#
这道题用treeset集合不是可以优化一下?不知道这样做是否符合题的要求?
回复 使用道具 举报
赞一个··谢谢分享
回复 使用道具 举报
汪泽蓉 来自手机 初级黑马 2016-5-11 12:47:56
11#
这个可以啊,点招题
回复 使用道具 举报
大赞,感谢分享啊。。。
回复 使用道具 举报
好长...................有点晕
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马