随机访问字符串数组

时间:2018-08-31 16:46:08

标签: java arrays java.util.random

我想将(.equals)字符串与用户输入进行比较,例如测验。现在我有多个问题:

1 如何才能随机访问我的字符串数组answerlist?(每次都像不同的(顺序)问题一样)我使用.random进行了如下尝试:

public String[] questionList = {"question1", "question2", "question3"};
// answer1 is the correct answer to question1 etc. 
public String[] answerList = {"answer1", "answer2", "answer3};
random = new Random();            
answer = answerList[random.nextInt(answerList.length)];

2 我以为我看到您可以使用(数组)列表而不是我现在使用的String数组。如果这是真的,请您详细说明如何执行此操作。以及如何随机访问。

3 ,我该如何将随机访问的答案与为用户显示的问题相匹配?我读过一些关于为此使用类的东西吗?

谢谢!

编辑:我只是想为每个问题和答案创建一个数组,然后以一种或其他方式访问它们?

2 个答案:

答案 0 :(得分:0)

您可以通过两种方法来实例化问题和答案列表。

1。使用班级提出问题及其相关答案

您可以考虑一个对象列表,每个对象都包含问题及其相关的答案。

class QuestionAnswerPair
{
    final String question;
    final String answer;

    public QuestionAnswerPair(@NonNull String question, @NonNull String answer)
    {
        this.question = question;
        this.answer = answer;
    }
}

然后将您的问题/答案添加到列表中,您将执行以下操作:

final List<QuestionAnswerPair> questionsAndAnswers = new ArrayList<>();
QuestionAnswerPair one = new QuestionAnswerPair("my question", "my answer");
questionsAndAnswers.add(one);
// keep creating and adding new questions and answers as needed

2。使用android.util.Pair

另一个选择是Android中的Pair utility class

final List<Pair<String, String>> questionsAndAnswers = new ArrayList<>();
questionsAndAnswers.add(Pair.create("question1", "answer1"));
//continue adding as needed

从这一点出发,要对列表进行混排,可以通过搜索“ java中的混排列表”或类似内容在Google中查找示例混排算法。可以在这里找到一个这样的示例:http://www.vogella.com/tutorials/JavaAlgorithmsShuffle/article.html

答案 1 :(得分:0)

  

我如何随机访问我的字符串数组答案列表?(每次都像不同的(顺序)问题一样。)

当您想更改测验/随机等问题时,建议您同时映射问题和答案。不推荐使用“混洗问题列表”和“答案列表”,也没有解决方案。

  

我想我看到您可以使用一个(array)list代替我现在使用的String数组。如果这是真的,请您详细说明如何执行此操作。以及如何随机访问。

     

如何将随机访问的答案与为用户显示的问题相匹配?我读过一些关于为此使用类的东西吗?

使用下面的Java Hashmap示例。

public class QuestionAnswers {
  public static void main(String[] args) {
    HashMap<String, String> questionSets = new HashMap<String, String>();
    questionSets.put("Question1", "Answer1");
    questionSets.put("Question2", "Answer2");
    questionSets.put("Question3", "Answer3");
    questionSets.put("Question4", "Answer4");
    questionSets.put("Question5", "Answer5");

    List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(questionSets.entrySet());

    System.out.println("************ Questions ************");
    Collections.shuffle(list);
    for (Map.Entry<String, String> entry : list) {
        System.out.println(entry.getKey());
        // Here entry.getKey() is Question and if user enters the correct answer 
        // match that answer with like -> "user_answer".equals(entry.getValue());
    }
  }
}
相关问题