Search code examples
javauser-interfacerandomjlabel

Random word from a dictionnary GUI


I am working on a game that selects a random word and the user have to find it in less than 7 mistakes, if he makes 7 mistakes he loses, if he makes less than 7 mistakes another word is given and his mistakes are kept. in the end the score is given.

I have a txt file dictionnary, and I wan't to know how to select a word from it and put it in a variable, then show this word hidden in stars * in a JLabel

thank you


Solution

  • What @HotLicks means is to use the Random class or Math.random(), both of which can create a random number. Let say you want to create random number between 0 and 99 inclisive. You would do something like this

    Random random = new Random();
    int randIndex random.nextInt(100);
    

    What the above does is give you a random index. We will use this random index to select a word.

    No to actually get the set of words, you need to get them into some kind of data structure, so you don't have to keep reading the file over and over. Let's say your file looks like this, every word on its own line

    Abba
    Zabba 
    Youre
    My
    Only
    Friend
    

    What you want to do is store those words into a data structure like a List. To that you need to read the file line by line, while adding each line to the List

    List<String> wordList = new ArrayList<String>();
    
    try {
        BufferedReader br = new BufferedReader(new FileReader("words.txt"));
        String line;
        while((line = br.readLine().trim()) != null) {
            wordList.add(line);
        }
    } catch (IOException ex){
        ex.printStackTrace();
    }
    

    Now the wordList has all the words from your file. And the randIndex variable holds a random index from the list. So you could do

    String randWord = wordList.get(randIndex);
    

    Of course though in the vary first piece of code in the this answer, you need to know the size of the list, before you can decide what number the random number should do up to. So after you populate the list, you would do something like this

    Random random = new Random();
    int randIndex = random.netInt(wordList.size());
    

    So every time you need a new word, just generate a new random number and use that numbers to get a word from the list at that index.


    Please see Basic I/O trail for more help with reading files.