将文件内容存储到数组中

我的刽子手程序有问题。 我真的认为我需要做的是超出我对java的理解。 这是我的代码

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Random; public class HangmanProject { public static void main(String[] args) throws FileNotFoundException { String scoreKeeper; // to keep track of score int guessesLeft; // to keep track of guesses remaining String[] wordList = new String[25]; final Random generator = new Random(); Scanner keyboard = new Scanner(System.in); // to read user's input System.out.println("Welcome to Nick Carfagno's Hangman Project!"); // Create a scanner to read the secret words file Scanner wordScan = null; try { wordScan = new Scanner(new BufferedReader(new FileReader("words.txt"))); while (wordScan.hasNext()) { } } finally { if (wordScan != null) { wordScan.close(); } } // get random word from array class pickRand { public String get(String[] wordList) { int rnd = generator.nextInt(wordList.length); return wordList[rnd]; } } System.out.println(wordList); } } 

我能够让程序读取文件,然后打印到屏幕,但我无法弄清楚如何将文件中的单词存储到数组中。 我根本没有进步,所以请尽量做到尽可能彻底。

您需要将读取行保存在String对象中,并将其分配给数组的某个字段。 例如:

 wordList[0] = myString; 

这会将myString的值赋给数组的第一个字段。

1)你到目前为止看起来很不错:)

2)因为你不确切知道你会有多少或几个单词,所以你不需要一个“数组”。 使用“ArrayList”可能会更好。 数组是“固定的”。 列表是“可变的”。

3)对于您阅读的每个“单词”,只需将“.add()”添加到您的arraylist中

瞧! 完成。

这是一个完整的例子: