Joe Joe - 7 months ago 13
Java Question

Array returning null .. Generate random word

I am trying to make a class for generating random words. So far my choices are

Scanner
or a
BufferReader
I am guessing.
This is the code that I think is most efficient however when I run I get
null
.

Also will a public return
randomWord
getter grant access to the word in main class?

private static final String filepath = "/assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words = new ArrayList<String>();


public void WordGenerator() {


rand = new Random();
String line;

try {

InputStream WordsFile = getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
if(!br.ready()){
System.out.println("No File");
}
else while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
}
catch (IOException e) {
System.out.println("Something is wrong");
}

int size = words.size();
Random rn = new Random();
int randWord = rn.nextInt(size);
randomWord = words.get(randWord);
System.out.println(randomWord);
}
}

Answer

I think what you really need to read your file is to remove the InputStream line and just replace the BufferedReader with this one:

BufferedReader br = new BufferedReader(new FileReader(filepath));

So your code will look like this:

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

public class WordGeneratorClass
{
   private static final String filepath="../assets/words.txt";
   public String randomWord;
   public Random rand;
   private ArrayList<String> words=new ArrayList<String>();

   public void WordGenerator()
   {
        rand=new Random();
        String line;

        try
        {
           BufferedReader br = new BufferedReader(new FileReader(filepath));

           if(!br.ready())
           {
            System.out.println("No File");
           }
           else while((line=br.readLine())!=null)
           {
              words.add(line);
           }
           br.close();
        }
        catch (IOException e)
        {
           e.printStackTrace();
        }

        int size=words.size();
        Random rn=new Random();
        int randWord=rn.nextInt(size);

        randomWord=words.get(randWord);

        System.out.println(randomWord);
   }

   public static void main(String args[])
   {
      WordGeneratorClass gen = new WordGeneratorClass();
      gen.WordGenerator();
   }
}

Ensure that your assets/words.txt exist.

Edit
Seems that the problem was also related to the path of your words.txt. The above code assumes that the assets/words/words.txt is in the same directory with the source code. For more information, please have a look here.

Comments