gpt4 book ai didi

java - 如何为字符串数组获取 10 个随机字符串?

转载 作者:行者123 更新时间:2023-12-02 03:08:24 25 4
gpt4 key购买 nike

大家好,我想知道如何创建一个方法,从 java 数组中的一组字符串(大约 96 个字符串)中随机获取 10 个字符串...

字符串取自文本文件我已经创建了一个方法来读取文件并将变量分配给行我还创建了一系列问题

这是我用于读取文件并创建问题数组的代码

q 是问题

选择一个

b ....

.

.

cA是正确答案

public static Question[] readAllQuestions() throws FileNotFoundException {
int numberOfQuestions = CountQuestions();
Question [] allQuestions = new Question[numberOfQuestions];
Scanner file = new Scanner (new File("TestBank.txt"));
String q = "";
String aa = "";
String bb = "";
String cc = "";
String dd = "";
String ccA = "";
int x = 0 ;
int k = 0 ;
while (x< (allQuestions.length-1)) {
while (file.hasNext() && k == 0) {
String ques[] = file.nextLine().split(" ");
for (int ww = 0 ; ww< ques.length ; ww++) {
q += ques[ww];
q+=" ";
}
if(ques[0].equals("")) {
k++ ;
}
}
while (k == 1) {
String a[] = file.nextLine().split(" ");
for (int ww = 0; ww< a.length; ww++) {
aa += a[ww];
aa+= " ";
}
if(a[0].equals("")) {
k++ ;
}
}
//file.hasNext() &&
while (k == 2) {
String b[] = file.nextLine().split(" ");
for (int ww = 0 ; ww< b.length ; ww++) {
bb += b[ww];
bb+= " ";
}
if(b[0].equals("")) {
k++;
}
}
while (k == 3) {
String c[] = file.nextLine().split(" ");
for (int ww = 0; ww<c.length; ww++) {
cc += c[ww];
cc+= " ";
}
if(c[0].equals("")) {
k++;
}
}
while (k == 4) {
String d[] = file.nextLine().split(" ");
for (int ww = 0; ww< d.length; ww++) {
dd += d[ww];
dd+= " ";
}
if(d[0].equals("")) {
k++;
}
}
while (k == 5) {
String cA[] = file.nextLine().split(" ");
for (int ww = 0; ww<cA.length; ww++) {
ccA += cA[ww];
ccA += " ";
}
if(cA[0].equals("")) {
k++;
}
}
while (k == 6) {
Question question = new Question(q,aa,bb,cc,dd,ccA);
allQuestions[x] = question;
q="";
aa="";
bb="";
cc="";
dd="";
ccA="";
x++;
k=0;
}
}
return allQuestions;
}

有什么想法吗?谢谢

最佳答案

在我看来,您想要从字符串数组中随机选择 10 个字符串,而不选择重复项。实现此目的的一种简单方法是使用 Collections::shuffle随机排列元素,然后选择打乱列表的子集。这是一个例子:

public static void main(String[] args) throws Exception
{
String[] exStringArray = IntStream.range(0, 96)
.mapToObj(Integer::toString)
.toArray(size -> new String[size]);

System.out.println(getRandomElements(Arrays.asList(exStringArray), 10));
}

private static <T> Collection<T> getRandomElements(Collection<T> c, int maxElements)
{
List<T> deepCopiedList = new ArrayList<>(c);
Collections.shuffle(deepCopiedList);
return Collections.unmodifiableList(deepCopiedList.subList(0, Math.max(Math.min(deepCopiedList.size(), maxElements), 0)));
}

关于java - 如何为字符串数组获取 10 个随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41417752/

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