0

I need to have this file print to an array, not to screen.And yes, I MUST use an array - School Project - I'm very new to java so any help is appreciated. Any ideas? thanks

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

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[];    // array to store words


        Scanner keyboard = new Scanner(System.in);    // to read user's input

        System.out.println("Welcome to 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()) {
                System.out.println(wordScan.next());
            }
        } finally {
            if (wordScan != null) {
                wordScan.close();
            }
        }
    }
}
Tim
  • 35,413
  • 11
  • 95
  • 121
Curly5115
  • 103
  • 1
  • 3
  • 13

3 Answers3

1

Do you need more help with the reading the file, or getting the String to a parsed array? If you can read the file into a String, simply do:

String[] words = readString.split("\n");

That will split the string at each line break, so assuming this is your text file:

Word1

Word2

Word3

words will be: {word1, word2, word3}

Alex Coleman
  • 7,216
  • 1
  • 22
  • 31
  • +1 nice idea :D - Wouldn't you need to configure the `Scanner` or would you simply read the file in as one long `String` – MadProgrammer Aug 24 '12 at 05:29
  • @MadProgrammer I was thinking just read in the whole thing first, then split it, as you could read it in line-by-line, but you don't know how big of an array you will need then. Split seems more effective here. But thanks :D – Alex Coleman Aug 24 '12 at 05:32
  • @AlexColeman: I think you would need to use a StringBuilder and append a `\n` for every word you read? – npinti Aug 24 '12 at 05:35
  • @AlexColeman That's the kind of thing I was think of (after you posted your answer), nice – MadProgrammer Aug 24 '12 at 05:37
  • I would replace `\r` with nothing before splitting so that `\rtest` isn't 5 characters – Cole Tobin Aug 24 '12 at 05:38
  • @npinti Yeah, that's one possible way of reading the scanner. – Alex Coleman Aug 24 '12 at 05:40
  • @ColeJohnson Actually, possibly replace \r with \n, as, correct me if I'm wrong, but I believe they are both line terminators and are just used differently by different applications – Alex Coleman Aug 24 '12 at 05:41
  • You are correct, replace `\r` with `\n` and split by `\n` and remove empty lines. Mac OS 9 and below used `\r`, Unix and OS X use `\n` and Windows uses `\r\n` – Cole Tobin Aug 24 '12 at 06:43
  • @MadProgrammer The issue is getting the strings to be put into an array. It's for a hangman program, so each word in the text file needs to be put into the array. I pretty much understand the "reading" of the file. But its the storing into an array that I'm confused about. Im gonna give this a try though. Thanks! And sorry about not being clear initially - late night programming had my head all screwy.... And I do know that the array is going to hold 10 words no matter what. I dont know if that makes things simpler.... or maybe worse haha – Curly5115 Aug 24 '12 at 18:39
1

If the words you are reading are stored in each line of the file, you can use the hasNextLine() and nextLine() to read the text one line at a time. Using the next() will also work, since you just need to throw one word in the array, but nextLine() is usually always preferred.

As for only using an array, you have two options:

  • You either declare a large array, the size of whom you are sure will never be less than the total amount of words;
  • You go through the file twice, the first time you read the amount of elements, then you initialize the array depending on that value and then, go through it a second time while adding the string as you go by.

It is usually recommended to use a dynamic collection such as an ArrayList(). You can then use the toArray() method to turnt he list into an array.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • Thanks. I know the size of the array. It has to be 10 elements large. (There are ten words in the file to be imported). And i would like to use the ArrayList() but my professor specifically instructed to not use ArrayList. Just because we didnt cover them. – Curly5115 Aug 24 '12 at 14:57
1

Nick, you just gave us the final piece of the puzzle. If you know the number of lines you will be reading, you can simply define an array of that length before you read the file

Something like...

String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
    wordArray[index] = word;
    index++;

Now that example's not going to mean much to be honest, so I did these two examples

The first one uses the concept suggested by Alex, which allows you to read an unknown number of lines from the file.

The only trip up is if the lines are separated by more the one line feed (ie there is a extra line between words)

public static void readUnknownWords() {

    // Reference to the words file
    File words = new File("Words.txt");
    // Use a StringBuilder to buffer the content as it's read from the file
    StringBuilder sb = new StringBuilder(128);

    BufferedReader reader = null;
    try {

        // Create the reader.  A File reader would be just as fine in this
        // example, but hay ;)
        reader = new BufferedReader(new FileReader(words));
        // The read buffer to use to read data into
        char[] buffer = new char[1024];
        int bytesRead = -1;
        // Read the file to we get to the end
        while ((bytesRead = reader.read(buffer)) != -1) {

            // Append the results to the string builder
            sb.append(buffer, 0, bytesRead);

        }

        // Split the string builder into individal words by the line break
        String[] wordArray = sb.toString().split("\n");

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

The second demonstrates how to read the words into an array of known length. This is probably closer to the what you actually want

public static void readKnownWords() 

    // This is just the same as the previous example, except we
    // know in advance the number of lines we will be reading    
    File words = new File("Words.txt");

    BufferedReader reader = null;
    try {

        // Create the word array of a known quantity
        // The quantity value could be defined as a constant
        // ie public static final int WORD_COUNT = 10;
        String[] wordArray = new String[10];

        reader = new BufferedReader(new FileReader(words));
        // Instead of reading to a char buffer, we are
        // going to take the easy route and read each line
        // straight into a String
        String text = null;
        // The current array index
        int index = 0;
        // Read the file till we reach the end
        // ps- my file had lots more words, so I put a limit
        // in the loop to prevent index out of bounds exceptions
        while ((text = reader.readLine()) != null && index < 10) {

            wordArray[index] = text;
            index++;

        }

        System.out.println("Read " + wordArray.length + " words");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }

}

If you find either of these useful, I would appropriate it you would give me a small up-vote and check Alex's answer as correct, as it's his idea that I've adapted.

Now, if you're really paranoid about which line break to use, you can find the values used by the system via the System.getProperties().getProperty("line.separator") value.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks so much for your help. I would love to give you an up-vote but i dont even have enough rep to up-vote you lol. I will as soon as i can though :) – Curly5115 Aug 24 '12 at 23:43
  • @NickCarfagno if you give Alex a nice nudge by accepting his answer, it will help you rep ;) – MadProgrammer Aug 24 '12 at 23:44