public class Test1 {
/**
* 1.写一个点名器,每当第三次点名都必定是张玮真帅
*/
public static void main(String[] args) throws IOException {
ArrayList<String> al = new ArrayList<>();
al.add("张三");
al.add("李四");
al.add("王五");
al.add("赵六");
al.add("周七");
// 点名器第一次运行,创建"count.txt"(保存的是点名的次数)和"index.txt"(保存的是点过名的索引(字符串))
int b;
try {
// 读取count.txt,得到点名次数
FileReader fr = new FileReader("count.txt");
b = fr.read();
fr.close();
} catch (Exception e) {
FileWriter fw = new FileWriter("count.txt");
fw.write(1);
fw.close();
FileWriter fw1 = new FileWriter("index.txt");
fw1.close();
System.out.println("欢迎使用<第三次必点张玮真帅>点名器!!");
return;
}
System.out.print("第" + b + "次点名:");
// 判断点名次数是否是第三次
if (b == 3) {
System.out.println("张玮真帅");
} else {
// 读取index.txt,按行存到hs集合中.
BufferedReader br = new BufferedReader(new FileReader("index.txt"));
HashSet<String> hs = new HashSet<>();
String line;
while ((line = br.readLine()) != null) {
hs.add(line);
}
br.close();
// 生成随机索引,保证索引不重复
Random r = new Random();
int i;
do {
i = r.nextInt(al.size());
} while (hs.contains(i + ""));
// 打印对应的名字,即点名
System.out.println(al.get(i));
// 在index.txt中添加点过名的索引(字符串)
BufferedWriter bw = new BufferedWriter(new FileWriter("index.txt",true));
bw.write(i + "");
bw.newLine();
bw.close();
}
// 判断点名是否完毕
if (b > al.size()) {
//点名完毕,删除"count.txt"和"index.txt"
File file1 = new File("count.txt");
file1.delete();
File file2 = new File("index.txt");
file2.delete();
System.out.println("点名完毕!!");
} else {
// 没点完,点名次数+1
FileWriter fw = new FileWriter("count.txt");
fw.write(++b);
fw.close();
}
}
}
|
|