每天一道Java小练习之抽取三位幸运儿

题目描述:

给定一个含有多人姓名的文件“xxx.txt”,再其中随机抽取三位幸运儿,将三位幸运儿的姓名写入“幸运儿.txt”。

注意:不允许使用乱序后取前三位

 实现思路:

1、读取"xxx.txt"中的所有姓名:Files.readAl1Lines(path);

2、随机抽取3个幸运儿(不重复)

3、将3个幸运儿的姓名写入"幸运儿.txt"

方式一: 

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

public class Demo07 {
	public static void main(String[] args) {
		try {
			//读取txt文件中的所有姓名
			List<String> names = Files.readAllLines(Paths.get("F:\\Apesource-java\\fsqlp\\xxx.txt"));
			for(String name : names) {
				System.out.println(name);
				System.out.println();
			}
			//随机抽取3个幸运儿
			LinkedHashSet<String> luckyer = new LinkedHashSet<String>();
			while (luckyer.size() < 3) {
                int index = (int) (Math.random() * names.size());
                String luckyName = names.get(index);
                luckyer.add(luckyName);
			}
			System.out.println(luckyer);
            //将3个幸运儿写入"幸运儿.txt"
            Files.write(Paths.get("F:\\Apesource-java\\fsqlp\\幸运儿.txt"),
                    luckyer,
                    Charset.forName("UTF-8"),
                    StandardOpenOption.APPEND  );
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

方式二:

public class Demo08 {
    public static void main(String[] args) {
        //读取”xxx.txt“中所有的姓名
        try {
            List<String> nameList = Files.readAllLines(Paths.get("F:\\Apesource-java\\fsqlp\\xxx.txt"));

            //随机抽取3个幸运儿(不重复)
            HashSet<String> lucky = new HashSet<String>();
            Random rand = new Random();
            
            for(;;) {
            	//产生1个随机下标,并根据下标获取对应的姓名
            	int randIndex = rand.nextInt(nameList.size());
            	String luckyer = nameList.get(randIndex);
            	
            	lucky.add(luckyer);
            	if(lucky.size() == 3) {
            		break;
            	}
            }
            System.out.println(lucky);
            //将3个幸运儿的名字写入”幸运儿.txt“
            Files.write(Paths.get("F:\\Apesource-java\\fsqlp\\幸运儿.txt"),
                    lucky);  
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值