0

I'm having an issue initiating a random word from the array. I'm not sure how to refer to the words arraylist to fetch from it. Can someone put me in the right direction for my getRandomWord class? Thanks!

A method getRandomWord which takes nothing as input and returns a random String from words. Remember that you can use the Random class to do this.

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

public class WordList{

  private ArrayList<String> words;

  //Construct String from file
  public static void constructor(String filename) throws IOException{

  ArrayList words = new ArrayList();
  BufferedReader read = new BufferedReader(new FileReader("filename"));
  String line = read.readLine();


    while (line != null){
      words.add(line);
      //line = reader.readline();
    }
  }

  public static void getRandomWord(){
Random rand = new Random();
String randomWord = words.get(rand.nextInt(words.size));
}
}
11
  • So you're trying to get a random word from a file and output it? Commented Dec 3, 2013 at 18:49
  • Member variables (e.g. 'words') cannot be referenced from static methods (e.g. 'getRandomWord()'). Either declare 'words' as static or remove 'static' keyword from method signature. Commented Dec 3, 2013 at 18:49
  • you should use something like : int rand= minimum + (int)(Math.random()*maximum); Commented Dec 3, 2013 at 18:50
  • Try this link maybe it will help you here Commented Dec 3, 2013 at 18:52
  • @TatakaiWasumi Indeed. From what I understand the first part of my code takes words from a file and puts them in an arraylist. The second part of my code needs to generate a random number and from that, output the corresponding word in the arraylist. I'm having issues with the fact that words is private... Says I can't reach it from getRandomWord Commented Dec 3, 2013 at 18:57

1 Answer 1

3

This will help you I think It's able to get a random word from an array of strings

private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
name = names[(int) (Math.random() * names.length)];
System.out.println(name);
Sign up to request clarification or add additional context in comments.

2 Comments

No problem. I hope your issue is fixed
@user3062703 You should click the checkmark to indicate that this answer solved your question.

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.