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();
            }
        }
    }
}
11
  • Why are you importing each class seperatly? Commented Aug 24, 2012 at 5:22
  • @ColeJohnson possibly the IDE Commented Aug 24, 2012 at 5:23
  • What do you mean by print to an array? And what is the problem that you're facing? Commented Aug 24, 2012 at 5:26
  • looks like you are doing a hangman app... Umm are you reading or writting to/from the file? Semms like it should be a read Commented Aug 24, 2012 at 5:26
  • refer it... would be helpful i guess... stackoverflow.com/questions/12085421/… Commented Aug 24, 2012 at 5:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
@NickCarfagno if you give Alex a nice nudge by accepting his answer, it will help you rep ;)
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}

9 Comments

+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 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
@AlexColeman: I think you would need to use a StringBuilder and append a \n for every word you read?
@AlexColeman That's the kind of thing I was think of (after you posted your answer), nice
I would replace \r with nothing before splitting so that \rtest isn't 5 characters
|
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.