-1

Trying to read about 25,000 words from file and put it in arraylist and selects random word from the arraylist. Stuck at creating array, filling array, randomly selecting the word in the array. But got a weird result.
Code:

package se.simple;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class WordHandler {

    public static void main(String[] args) {

        List<String> words = new ArrayList<String>();
        try (BufferedReader br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                            words.add(sCurrentLine);
                System.out.println(words);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


Everything is printed out in one line. But now I need to randomly select a word from arraylist.

[10th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, a, AAA, AAAS, Aarhus, Aaron, AAU, ABA, Ababa, aback, abacus, abalone, abandon, abase, abash, abate, abater, abbas, abbe, abbey, abbot, Abbott, abbreviate, abc, abdicate, abdomen, abdominal, abduct, Abe, abed, Abel, Abelian, Abelson, Aberdeen, Abernathy, aberrant, aberrate, abet, abetted, abetting, abeyance, abeyant, abhorred, abhorrent, abide, Abidjan, Abigail, abject, ablate, ablaze, able, ablution, Abner, abnormal, Abo, aboard, abode, abolish, abolition, abominable, abominate, aboriginal, aborigine, aborning, abort, abound, about, above, aboveboard, aboveground, abovementioned, abrade, Abraham, Abram, Abramson, abrasion, abrasive, abreact, abreast, abridge, abridgment, abroad, abrogate, abrupt, abscess, abscissa, abscissae, absence, absent, absentee, absenteeism, absentia, absentminded, absinthe, absolute, absolution, absolve, absorb, absorbent, absorption, absorptive, abstain, abstention, abstinent, abstract, abstracter, abstractor, abstruse, absurd, abuilding, abundant, abusable, abuse, abusive, abut, abutted, abutting, abysmal, abyss, Abyssinia, AC, academe, academia, academic, academician, academy, Acadia, acanthus, Acapulco, accede, accelerate, accelerometer, accent, accentual, accentuate, accept, acceptant, acceptor, access, accessible, accession, accessory, accident, accidental, accipiter, acclaim, acclamation, acclimate, accolade, accommodate, accompaniment, accompanist, accompany, accomplice, accomplish, accord, accordant, accordion, accost, account, accountant, Accra, accredit, accreditate, accreditation, accretion, accrual, accrue, acculturate, accumulate, accuracy, accurate, accusation, accusative, accusatory, accuse, accustom, ace, acerbic, acerbity, acetate, acetic, acetone, acetylene, ache, achieve, Achilles, aching, achromatic, acid, acidic, acidulous, Ackerman, Ackley, acknowledge, acknowledgeable, ACM, acme, acolyte, acorn, acoustic, acquaint, acquaintance, acquiesce, acquiescent, acquire, acquisition, acquisitive, acquit, acquittal, acquitting, acre, acreage, acrid, acrimonious, acrimony, acrobacy, acrobat, acrobatic, acronym, acropolis, across, acrylate, acrylic, ACS, act, Actaeon, actinic, actinide, actinium, actinolite, actinometer, activate, activation, activism, Acton, actor, actress, Acts, actual, actuarial, actuate, acuity, acumen, acute, acyclic, ad, Ada, adage, adagio, Adair, Adam, adamant, Adams, Adamson, adapt, adaptation, adaptive, add, added, addend, addenda, addendum, addict, Addis, Addison, addition, additional, additive, addle, address, addressee, Addressograph, adduce, Adelaide, Adele, Adelia, Aden, adenine, adenoma, adenosine, adept, adequacy, adequate, adhere, adherent, adhesion, adhesive, adiabatic, adieu, adipic, Adirondack, adjacent, adject, adjectival, adjective, adjoin, adjoint, adjourn, adjudge, adjudicate, adjunct, adjust, adjutant, Adkins, Adler, administer, administrable, administrate, administratrix, admiral, admiralty, admiration, admire, admissible, admission, admit, admittance, admitted, admitting, admix, admixture, admonish, admonition, ado, adobe, adolescent, Adolph, Adolphus, Adonis, adopt, adoption, adoptive, adore, adorn, adposition, adrenal, adrenaline, Adrian, Adriatic, Adrienne, adrift, adroit, adsorb, adsorbate, adsorption, adsorptive, adulate, adult, adulterate, adulterous, adultery, adulthood, advance, advantage, advantageous, advent, adventitious, adventure, adventurous, adverb, adverbial, adversary, adverse, advert, advertise, advice, advisable, advise, advisee, advisor, advisory, advocacy, advocate, Aegean, aegis, Aeneas, Aeneid, aeolian, Aeolus, aerate, aerial, Aerobacter, aerobic, aerodynamic, aerogene, aeronautic, aerosol, aerospace, Aeschylus, aesthete, aesthetic, afar, affable, affair, affect, affectate, affectation, affectionate, afferent, affiance, affidavit, affiliate, affine, affinity, affirm, affirmation, affirmative, affix, afflict, affluence, affluent, afford, afforest, afforestation, affricate, affront, Afghan, Afghanistan, aficionado, afield, afire, aflame, afloat, afoot, aforementioned, aforesaid, aforethought, afoul, afraid, afresh, Africa, afro, aft, aftereffect, afterglow, afterimage, afterlife, aftermath, afternoon, afterthought, afterward, afterword, again, against, Agamemnon, agate, Agatha, agave, age, Agee, agenda, agent, agglomerate, agglutinate, agglutinin, aggravate, aggregate, aggression, aggressive, aggressor, aggrieve, aghast, agile, aging, agitate, agleam, Agnes, Agnew, BUILD STOPPED (total time: 30 seconds)
JustinBieber
  • 355
  • 3
  • 5
  • 23
  • I am not sure I like the idea of helping "JustinBieber". Do you just need to select a few words or lots of words? – AtlasMeh-ed Nov 17 '14 at 18:57
  • 1
    Let's put it this way: how much of your code do you understand? – Olavi Mustanoja Nov 17 '14 at 19:01
  • @AtlasMeh-ed you just don't want to help me because of my alias? I need to select one word from the array. Been a while since I coded java. – JustinBieber Nov 17 '14 at 19:46
  • @OlaviMustanoja It's just a method to read a file and dump in a text to write out current texts. If you don't want to help you just could stay away. I don't need your comments, it's not encouraging. – JustinBieber Nov 17 '14 at 19:47
  • @JustinBieber haha no it's just a joke. I put an answer below. If you work on your code and get a little closer to a working solution I'll be happy to help. Feel free to message me with any questions. Also you'll get more help the closer you are to a solution. So lets say you have a problem reading in the file to a list. Ask a question about that instead of the whole problem. Good luck! – AtlasMeh-ed Nov 17 '14 at 20:06
  • @AtlasMeh-ed maybe the question is not directed for you. Some people prefers to see the big picture rather than a detail part. My question includes both the big picture and details of what I'm trying to achieve. Good luck you too. Hang in there. – JustinBieber Nov 17 '14 at 20:23

3 Answers3

2

Hmm I don't want to just do this all for you. It seems like it's an assignment. I will however give a template for how you could do it.

  1. Create a method that just reads in the words file to an array list of words.

  2. Create a method that randomly picks an element from your list of words.

  3. In your main method call on method 1 to create your word list. Call on method 2 as many times as you need to in order to print off enough random words.

AtlasMeh-ed
  • 469
  • 5
  • 7
1

look at this 2 things and try to modify this code that i wrote. How do I generate random integers within a specific range in Java? String array initialization in Java

        BufferedReader br = null;

        String words[] = new String[4];
        int i=0;
        try {

            String sCurrentLine;
            String word; 

            br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                words[i]=sCurrentLine;
                i++;
            }

            Random rn = new Random();
            int x = rn.nextInt(3)+1;
            System.out.println(words[x]);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
Community
  • 1
  • 1
1
package se.simple;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class WordHandler {

    public static void main(String[] args) {

        //1. Create an array
        List<String> words = new ArrayList<String>();

        //2. Read a file line by line and add file words to words array.
        try (BufferedReader br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt"))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                words.add(sCurrentLine);
                //System.out.println(words);
            }

            System.out.println(words);

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(words.size());

        //3. Randomizing to pick up a word from arraylist
        Random rand = new Random();
        int randomNumber = rand.nextInt(words.size() - 1) + 1;

        System.out.println(randomNumber);

        //4. Prints the randomly selected word. 
        String word = words.get(randomNumber);
        System.out.println(word);

        //5. Gets the word length.
        int dashedWord = word.length();
        System.out.println(dashedWord);

        //6. Prints the word as dashes. 

         for(int x = 0; x < dashedWord; x = x+1) {
         System.out.print("-");
        }
    }
}
JustinBieber
  • 355
  • 3
  • 5
  • 23