dimanche 1 mai 2016

Array returning null .. Generate random word

Im trying to make a class for generating random words.. so far my choices are scanner or a bufferreader im guessing.. this is the code that i think is most efficient however wen i run i get null null 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);
}

}




Aucun commentaire:

Enregistrer un commentaire