简体   繁体   中英

How do I read a populated array from a .txt file?

I have a .txt file that is filled with 87 four letter words. I am essentially making a hangman game in which the user starts the game, and a random number is generated between 0 and 86 and then the program goes to the .txt file and picks out that word for the user to guess. This is the first time I am trying to do this because I am a new programming student and the book I am using is little to of no help at all. SO...here is what I have been doing for this:

class ReturnRandomInteger {

    public int randomInteger() {
        int randomInt = 0;
        for (int i = 0; i < 1; i++) {
        randomInt = (int) (Math.random() * 86) + 0;
    }
return randomInt;
}
    public static String getWord(int randomInt, String line) {
        FourLetterWords newObject = new FourLetterWords();
        if (randomInt == String line)

    }
}

class FourLetterWords {

    public static void readFile() {

    try {
        String fileName = "C//FourLetterWords.txt";
        File fourLetterWords = new File(fileName);
        Scanner in = new Scanner(fourLetterWords);

        ArrayList<FourLetterWords> words = new ArrayList<>();

        while (in.hasNextLine()) {
            String line = in.nextLine();
        }

    } catch (FileNotFoundException ex) {
    System.out.println("File not found.");
    }
}
}

For starters, I don't know if my try and catch is correct. The name of the file is FourLetterWords.txt. If it is wrong I want to know what the correct way to read each line in the .txt file is. Now in my ReturnRandomInteger class, I created the new object from my FourLetterWords class and you could see that what I am trying to do is have it so that if the random integer the user generated equals the corresponding line in the .txt file then it will return that word in that line. Obviously, int can not equal a String so how am I supposed to correspond the integer generated with the word in the .txt file I have?

I would greatly appreciate any help that I can get.

Try something like this:

    String fileName = "C:\\FourLetterWords.txt";
    File fourLetterWords = new File(fileName);
    Scanner in = new Scanner(fourLetterWords);

    ArrayList<String> words = new ArrayList<String>();

    while (in.hasNextLine()) {
        words.add(in.nextLine());
    }

Now your words will be stored in words arraylist and you can access with your random number like:

    words.get(randomNumber);

As the whole random number part is pretty much only one line of code and the getWord method should logically not be in the class that provides a random number I put together one class to do the whole work.

I would advise to make the fileName dynamic as well (eg adding a parameter to the RandomWordProvider constructor), but decided against it to keep it a bit more simple.

class RandomWordProvider {

    private List<String> words;

    public RandomWordProvider() {
        words = readFile();
    }

    private int randomInteger() {
        int randomInt = (int) (Math.random() * words.size());
        return randomInt;
    }

    public String getWord(int randomInt, String line) {
        int randomPosition = randomInteger();
        String randomWord = words.get(randomPosition);
        return randomWord;
    }

    private List<String> readFile() {

        List<String> wordsList = new ArrayList<>();

        try {
            String fileName = "C:/FourLetterWords.txt";
            File fourLetterWords = new File(fileName);
            Scanner in = new Scanner(fourLetterWords);

            while (in.hasNextLine()) {
                String line = in.nextLine();
                if (line!=null && !line.isEmpty()) {
                    wordsList.add(line);
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("File not found.");
        }

        return wordsList ;
    }
}

I removed the static access to getWord, so you have to initialize the object and the file gets read initially.

randomInteger: I changed the function to calculate it, so it takes the list's size and is flexible if you want to add more words later. The method Math.random() will never return 1, so for your 87 elements the number will be between 0 and (in your example) 86.999... where the cast to int will just cut off the decimal part.

getWord: The method fetches a random value as a position indicator in the words list. It then gets the random word out of your list and finally returns it.

readFile: Pretty much what you already did, I added a check for null and empty Strings and it then adds the word to the array that is later returned. As far as I know Java doesn't much care about what slashes you use in a path, I switched from OS-dependant paths to always using the 'normal' slash at one point...

This is drycoded, so I hope I did not miss anything, I especially did not check the whole part of reading the lines using Scanner... :) To make it a bit more comprehensible I decided to write some more lines of code than necessary, randomInteger() and getWord() can be done in one line if desired ;)

Create an array of Strings (lets assume, you name it words[] ). At start of the program, read lines from your file one by one, and store them in the array ( words[i++]=line ). Now, when you need to select a word, just do word = words[randomInt] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM