gpt4 book ai didi

java - 从数组中随机选择元素,而不选择两次

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

我有 2 个数组,它们以相同的方式进行洗牌。基本上,一旦被要求避免打印出重复项,我想删除数组元素:

我该如何解决这个问题,我需要使用数组列表吗?我完全迷失了。

/*
* *** Random Test ***
* Allows the user to generate a random test
* from a bank of 10 questions.
*/

// import java libraries
import java.util.Scanner;
import java.util.Random;

public class randomTest {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);


// Question bank
String[] qBank = new String[] {"What is the capital of England?",
"Which animal comes first in the English dictionary",
"How many days are there in a leap year?"};

// Answer bank
String[] aBank = new String[] {"London",
"Aardvark",
"366"};

// How many questions?
System.out.println("How many questions would you like? (1-10)");
int numQuestions = Integer.parseInt(sc.nextLine());
int asked = 0;

// Already Asked
int[] alreadyAsked = new int[numQuestions];


while (numQuestions != asked) {

// Random question
int idx = new Random().nextInt(qBank.length);
String question = (qBank[idx]);
System.out.println(question);


System.out.println("Enter your awnswer: ");
String myAnswer = sc.nextLine();
asked ++;


if (myAnswer.equals(aBank[idx])) {
System.out.println("Correct answer!");
} else {
System.out.println("Wrong answer");
}
}
}
}

最佳答案

使用ArrayList<String>将是您最好的解决方案,那么您可以这样做 list.remove()删除使用的条目。

Collections.shuffle() 将打乱一个列表。不过,您可能真正想做的只是每次循环时从列表中随机选择一个元素:

 List<String> questions = new ArrayList<>();
questions.add("question 1");
questions.add("question 2");
etc
List<String> answers = new ArrayList<>();
answers.add("answer 1");
etc

Random random = new Random();

while (questionsRemaining-- > 0) {
int q = random.nextInt(questions.size());
// ask question questions.get(q);
// check against answer answers.get(q);

// Removed used
questions.remove(q);
answers.remove(q);
}

实际上,虽然您最好定义一个 Question 对象并在其中包含 Q 和 A,但您不必维护两个列表,并且将来您可以添加更多数据(例如不同问题的不同分数,多个答案等)。

关于java - 从数组中随机选择元素,而不选择两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238738/

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