我希望编译器randomly
从文本中选择一个单词,而不是从文本文件中打印所有内容。现在,下面的代码是打印文本文件中的所有内容。我认为我的getWord
方法存在问题,因为当我从main函数调用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");
}
}
}
答案 0 :(得分:0)
在openfile方法中你重新调整了一个&#34; word&#34;变量是 null为变量赋值
错误来自{getword();},因为您正在访问 null变量的属性是一个错误
public List<String> readFile() throws FileNotFoundException {
while(file.hasNext()){
String a = file.nextLine();
words.add(a);
System.out.println(a);
}
return words;
}
在return语句行调用&#34;中打开文件方法;返回readfile();&#34;并尝试你的代码\
无需在main方法中调用readfile方法
答案 1 :(得分:0)
您在调用getWord方法时遇到异常,因为它会在行IndexOutOfBoundsException
处抛出String randomWord = words.get(r.nextInt());
。
对getWord
方法的PFB修正:
public String getWord() {
//You can use any approach..Random or Collections
//Random r = new Random();
//String randomWord = words.get(r.nextInt(words.size()));
Collections.shuffle(words);
String randomWord = words.get(1);
return randomWord;
}
您应该再次正确填充words
字段:
public void readFile() throws FileNotFoundException {
words = new ArrayList<String>();
while (file.hasNext())
words.add(file.nextLine());
}
答案 2 :(得分:0)
试试这个。您不需要在main中使用getWord()方法。 另外,为类创建一个构造函数:
public TextFile() {
}
你的openFile()方法不需要返回字符串。
private void openFile() {
try {
file = new Scanner(new File("words.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (Exception e) {
System.out.println("IOEXCEPTION");
}
}
这是你的readFile()方法: 1)读取文件 2)将一行单词分成每个单词并将其放入数组中 3)然后,随机单词
public void readFile() throws FileNotFoundException {
// List<String> wordList = new ArrayList<String>();
while(file.hasNext()){
String line = file.nextLine(); //read file one line at a time
String[] parseWords = line.split(" "); //Parse what you read
int index = new Random().nextInt(parseWords.length);
String randW = parseWords[index];
System.out.println(randW);
}
}
在您的主要方法中:
TextFile file1 = new TextFile ();
file1.openFile();
file1.readFile();
file1.closeFile();