gpt4 book ai didi

java - 从数组列表中获取随机单词

转载 作者:行者123 更新时间:2023-12-01 13:09:07 24 4
gpt4 key购买 nike

我想在 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() {

}
}

最佳答案

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

关于java - 从数组列表中获取随机单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com