1

I am writing small game and I need to read off text file, write it into array and then print array. My class for reading and returning array looks like this:

import java.io.*;
import java.util.*;

public class WordsList {

    public String[] wordsList;


    public void readFile() throws Exception{

        FileInputStream in = new FileInputStream("test.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        NumberOfLines read = new NumberOfLines();
        int n = read.getLineCount();

        String strLine;
        wordsList = new String[n];   

        for (int j = 0; j < wordsList.length; j++){
        wordsList[j] = br.readLine();

        }
        in.close();
    }

    public String[] returnsWordList(){
        return wordsList;
    }
}

And in main class I have this:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) throws Exception {
        WordsList words = new WordsList();
        System.out.println(words.returnsWordList());
    }

}

It returns null value rather than words... What did I do wrong? Any ideas?

1 Answer 1

2

What did I do wrong? Any ideas?

You failed to call readFile() anywhere in your code. Change your main method to:

WordsList words = new WordsList();
words.readFile();
System.out.println(words.returnsWordList());

and it will probably print out a non-null reference. It won't be a useful representation, because arrays don't override toString. If you want to see that actual contents, you'd want:

System.out.println(Arrays.toString(words.returnsWordList()));

There are various other ways in which your code is still far from great, but that should at least get you started.

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

1 Comment

Thanks, I changed code too many times and lost myself, I had it done properly, but I forgot about toString. (Java noob here) Thanks!

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.