java希望从文本文件中随机选择word,而不是从文本文件中打印所有内容
我希望编译器randomly
从文本中选择一个单词,而不是从文本文件中打印所有内容。现在,下面的代码正在打印文本文件中的所有内容。我认为我的getWord
方法有问题,因为当我从主函数调用getWord
方法时,我得到一个error
public class TextFile {
protected static Scanner file;
protected static List<String> words;
public TextFile(){
words = openFile();
}
private List<String> openFile() {
//List<String> wordList = new ArrayList<String>();
try {
file = new Scanner(new File("words.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (Exception e) {
System.out.println("IOEXCEPTION");
}
return words;
}
public void readFile() throws FileNotFoundException {
//ArrayList<String> wordList = new ArrayList<String>();
while(file.hasNext()){
String a = file.nextLine();
//Collections.shuffle(words);
//String pickWord = words.get(1);
//String[] a =
System.out.println(a);
}
}
public void closeFile() {
file.close();
}
public String getWord() {
Random r = new Random(words.size());
String randomWord = words.get(r.nextInt());
//System.out.println(randomWord);
return randomWord;
}
public static void main(String[] args) throws FileNotFoundException {
try {
TextFile file = new TextFile();
file.openFile();
file.readFile();
file.closeFile();
} catch (Exception e) {
System.out.println("IOEXCEPTION");
}
}
}
# 1 楼答案
在openfile方法中,您正在重新调整一个“word”变量,该变量是 null为变量赋值
错误来自{getword();}因为你正在访问 空变量的属性是一个错误
在返回语句行调用“return readfile();”的open file方法中试试你的代码
不需要在main方法中调用readfile方法
# 2 楼答案
调用getWord方法时,在第
String randomWord = words.get(r.nextInt());
行抛出IndexOutOfBoundsException
时出现异常PFB对
getWord
方法的修正:同样,您应该正确填充
words
字段:# 3 楼答案
试试这个。不需要在main中使用getWord()方法。 另外,为类创建构造函数:
openFile()方法不需要返回字符串
以下是readFile()方法: 1) 读取文件 2) 将一行单词拆分为每个单词,并将其放入数组中 3) 然后,随机词
在你的主要方法中: