读取从文件到数组的单词,并从数组中随机选择一个单词

时间:2014-11-17 18:55:28

标签: java arrays

尝试从文件中读取大约25,000个单词并将其放入arraylist并从arraylist中选择随机单词。坚持创建数组,填充数组,随机选择数组中的单词。但得到了一个奇怪的结果。
代码:

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();
        }

    }
}


所有东西都打印成一行。但现在我需要从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)

3 个答案:

答案 0 :(得分:1)

嗯,我不想一直为你做这一切。这似乎是一项任务。但是,我会给出一个模板,说明如何做到这一点。

  1. 创建一个方法,只需将单词文件读入数组的单词列表。

  2. 创建一个从单词列表中随机选取元素的方法。

  3. 在main方法中调用方法1来创建单词列表。根据需要多次调用方法2,以便打印足够的随机单词。

答案 1 :(得分:0)

看看这两件事,并尝试修改我写的这段代码。  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();
            }
        }

答案 2 :(得分:0)

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("-");
        }
    }
}