qq_34214381 2016-03-08 07:59 采纳率: 50%
浏览 6329
已采纳

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

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

  • 写回答

2条回答 默认 最新

  • IT丶小农民 2016-03-08 08:50
    关注
     import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    
    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();
            } 
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作