使用IO流写一个随机点名程序
前言
最近学习了关于IO流的一些知识点,但是应用还不够,所以今天做个简单案例:
随机创建名字导入文件中:
package ioandcollection;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Random;
public class example02 {
public static void main(String[] args) throws IOException{
ArrayList<String> names = new ArrayList<>();
String[] surnames = {"张", "王", "李", "赵", "刘", "陈", "杨", "黄", "周", "吴"};
String[] maleNames = {"伟", "强", "磊", "军", "勇", "杰", "峰", "浩", "敏", "飞"};
String[] femaleNames = {"芳", "娜", "婷", "秀", "霞", "敏", "莉", "红", "萍", "玲"};
Random random = new Random();
for (int i = 0; i < 15; i++) {
String surname = surnames[random.nextInt(surnames.length)];
String name;
if (random.nextBoolean()) { // 随机选择男女
name = maleNames[random.nextInt(maleNames.length)];
} else {
name = femaleNames[random.nextInt(femaleNames.length)];
}
names.add(surname + name);
}
writeName(names);
}
public static void writeName(ArrayList<String> names) throws IOException {
String target = "filemould//students.txt";
System.out.println(names);
BufferedWriter wb = new BufferedWriter(new FileWriter(target));
for (String name : names) {
wb.write(name);
wb.newLine();
wb.flush();
}
wb.close();
}
}
将名字导出存储在集合中,然后随机点名:
package ioandcollection;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
/*
* 需求:有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器。
思路:
① 把文件中的数据读取到到集合中
② 使用Random产生一个随机数,获得随机索引。
③ 通过随机索引获取随机姓名
* */
public class example01 {
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<>();
String content = "filemould\\students.txt";
readFileContent(content,list);
//产生一个随机数,获得随机索引
Random random = new Random();
int randomIndex = random.nextInt(list.size());
//获取随机数姓名
String randomName = list.get(randomIndex);
System.out.println("被点到的同学是:" + randomName);
}
private static void readFileContent(String content,ArrayList<String> list) throws IOException {
BufferedReader br = null;
//创建文件字节缓冲输入流对象
br = new BufferedReader(new FileReader(content));
//一次读取一个字符
String name;
while((name = br.readLine())!=null){
list.add(name);
}
System.out.println(list);
br.close();
}
}
总结:
1、wb.newLIne()可以将光标移动到下一行
2、br.readLine()可以读取下一行的内容
本文来自博客园,作者:news_one,转载请注明原文链接:https://www.cnblogs.com/new-one/p/17824908.html