我一直在尝试很多事情,我只是准备寻求一些帮助。如果这还不够信息,请告诉我。我已经尝试过Scanner,BufferReader等搜索帖子,但没有运气。
我words.txt在 src 目录中有该文件。
导入java.io.File;
导入 java.util.ArrayList;
导入 java.util.Random;
导入 java.util.Scanner;
/*
* 处理随机获取和设置秘密词的类
*/
公共类secretWord {
私有 ArrayList theWordList;
私人扫描仪扫描仪;//用于将文件读入数组
私人随机随机;//生成随机数索引,用于选择随机数组元素
私有整数随机索引;//保存生成的随机索引
ArrayList theSecretWord= new ArrayList(); //将密字转换成char[]供程序使用
字符串 tempSecretWord;//秘密单词被选为字符串
//构造函数:运行方法来创建单词数组列表,然后为这些秘密词选择一个随机元素
公共秘密字(){
创建数组();
getSecretWord();
}
//从文件中创建一个单词的ArrayList
私人无效createArray(){
theWordList=new ArrayList();
字符串文件= getClass().getResource("words.txt").getPath();
文件 f= 新文件(文件);
尝试{
扫描仪扫描仪=新的扫描仪(f);
而(扫描仪。hasNext()){
theWordList.add(scanner.nextLine());
}
}catch(异常 e){
e.printStackTrace();
}最后{
扫描仪.close();
}
}
//从ArrayList中选择一个随机数作为密码词
私人无效getSecretWord(){
随机=新随机();
randomIndex=random.nextInt(theWordList.size());
theSecretWord.add(theWordList.get(randomIndex).toUpperCase());
}
//删除secretWord并获得一个新的用于另一场比赛
无效刷新字(){
theSecretWord.clear();
getSecretWord();
}
}