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

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

public class Test15 {
        /*
         * 3.从键盘接受多个int型的整数,直到用户输入end结束, 要求:把所有的整数按倒序写到D:\\number.txt中
         *
         * 思路:
         *  用nextLine接收, Integer.parseInt()转成数字, 存到list集合中, 排序list集合, 倒着遍历输出到文本中
         */
        public static void main(String[] args) throws IOException {
                // 创建键盘录入对象
                Scanner sc = new Scanner(System.in);
                // 创建List集合存入键入值
                List<Integer> al = new ArrayList<>();
                // 提示输入
                System.out.println("请输入整数,end结束。");
                // 循环
                while (true) {
                        // 定义个line接收键入的字符串
                        String line;
                        // 判断是否是end结束语,是的话跳出循环
                        if ("end".equals(line = sc.nextLine())) {
                                break;
                                // 如果不是end就将值存入list集合中。
                        } else {
                                // 如果键入的不是end,又非整数。将提示输入错误!
                                try {
                                        al.add(Integer.parseInt(line));
                                } catch (Exception e) {
                                        System.out.println("你输入的不是整数或end");
                                }

                        }
                }
                // 创建输出流
                BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\number.txt"));
                // 倒着循环遍历进文件中。
                for (int i = al.size() - 1; i >= 0; i--) {
                        // 用get();方法提取集合中的元素,并将其转成字符串。
                        bw.write(al.get(i) + " ");
                }
                // 关闭流。
                bw.close();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马