我有两个以相同方式洗牌的数组。基本上我想删除数组元素一旦被要求避免重复打印出来:
如何解决此问题,是否需要使用数组列表?我完全迷失了。
/*
* *** 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");
}
}
}
}
答案 0 :(得分:1)
使用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,那么你不必维护两个列表,并且将来你可以添加更多数据(比如不同问题的不同分数,多个答案,等等。)
答案 1 :(得分:0)
如果您不想复制,请使用Set。要从List中删除重复项,可以使用Set s = new HashSet(list);
答案 2 :(得分:0)
使用2D数组并一起设置问题和答案。
String[][] example = new String[2][10];
example[0, 0] = "What is the capital of England?";
example[1, 0] = "London";
您不必以繁琐的方式输入它,它适用于您上面的数组实例化(使用{})。
或者,ArrayList<String[]>
。只需将String[]
设置为{"question", "answer"}
,然后将其添加到ArrayList
。