有一个1-50的数组,每次随即不重复抽取7个数,取7次,将这49个数写入到文件,剩下那个数显示在屏幕,程序应该怎么写?
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();
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。