开发者社区> 问答> 正文

java中如何将输出的结果写入到文件和显示在屏幕

有一个1-50的数组,每次随即不重复抽取7个数,取7次,将这49个数写入到文件,剩下那个数显示在屏幕,程序应该怎么写?

展开
收起
蛮大人123 2016-06-03 13:51:44 4602 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    public class Demo {
    public static Random ran = new Random();
        public static void main(String[] args) {
            try {
                solution();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //获取50个随机数
        public static List<Integer> test() {
            List<Integer> arr = new ArrayList<Integer>();
            for (int i = 0; i < 50; i++) {
                arr.add(i+1);
            }
            return arr;
        }
        //逻辑处理
        public static  void solution() throws Exception{
            List<Integer> res = new ArrayList<Integer>();
            List<Integer> list = test();
            for (int i = 0; i < 7; i++) {
                for(int j = 0; j< 7;j++){
                    int a = ran.nextInt(list.size());
                    res.add(list.get(a));
                    list.remove(list.get(a));
                }
            }
            write2Txt(res.toString());//写到文本
            System.out.println("50个数字剩余的最后一个数字="+list.get(0));//输出到控制台
        }
         //字符串写出到文本
        public static void  write2Txt(String str) throws Exception{
            FileWriter fw = null;
            String path = "C:\\Users\\db2admin\\Desktop\\txt.txt";
            File f = new File(path);
            try {
                if (!f.exists()) {
                    f.createNewFile();
                }
                fw = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fw);
                // FileOutputStream fos = new FileOutputStream(f); 
                // OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8"); 
                out.write(str.toString());
                out.close();
                System.out.println("===========写入文本成功========");
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    }
    2019-07-17 19:26:31
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载