作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
大家好,我想知道如何创建一个方法,从 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/
我是一名优秀的程序员,十分优秀!