从arraylist中获取一个随机单词

时间:2014-04-12 16:09:26

标签: java random arraylist

我想从方法getRandom中的ArrayList中获取一个随机单词。我的ArrayList是从一个文件加载的。然后我将在刽子手游戏中使用这个词。所以我希望它打印得像 * ****

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


public class Application {
    private ArrayList<Pirateword> piratewords;
    private Scanner input;

    public Application(){
        input=new Scanner(System.in);
        piratewords=new ArrayList<Pirateword>();

    }

    public void runApplication() throws IOException {

        String response;
        String w;
        do {

            load("piratewords.txt");
            save("piratewords.txt");
            response=input.nextLine();


    } while (!((response.equals("q")|| (response.equals("q")))));
        System.out.println("Thank you for playing");
    }




    public void load(String fileName) throws IOException{
        Scanner infile =new Scanner(new InputStreamReader(new FileInputStream(fileName)));
        int num=infile.nextInt();infile.nextLine();
        for (int i=0;i<num;i++) {
            String w=infile.nextLine();
            Pirateword p=new Pirateword(w);
            piratewords.add(p);
        }
        infile.close();
    }

    public void save(String fileName) throws IOException{
        PrintWriter outfile = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName)));
        outfile.println(piratewords.size());
        for (Pirateword p:piratewords) {
            outfile.println(p.toString());
        }
        outfile.close();
    }

    public void getRandom() {

}
}

3 个答案:

答案 0 :(得分:1)

public String getRandom() {
    return piratewords.get(new Random().nextInt(piratewords.size());
}

答案 1 :(得分:0)

将此添加到构造函数中。

Random gen = new Random();

在你的方法中,使用它在你的arraylist中返回随机字符串

public String getRandom() {
    int index = gen.nextInt(piratewords.size());
    return piratewords.get(index);
}

答案 2 :(得分:0)

如果对原始列表中的项目进行随机播放没有任何损害,请尝试使用Collections.shuffle()

注意:如果列表中有大量商品,请不要使用它。

if(piratewords.size()>0){
    Collections.shuffle(piratewords);
    System.out.println(piratewords.get(0));
}