猿问

随机访问字符串数组

我想将 ( .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 我以为我看到您可以使用(数组)列表代替我现在使用的字符串数组。如果这是真的,请您解释一下如何做到这一点。以及如何随机访问。


3以及如何将随机访问的答案与为用户显示的问题相匹配?我读了一些关于为此使用类的信息?


提前致谢!


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


海绵宝宝撒
浏览 204回答 2
2回答

Helenr

我如何随机访问我的字符串数组答案列表?(每次都像不同的(顺序)问题)。由于您想更改测验/随机等问题,建议您将问题和答案映射在一起。洗牌问题列表和答案列表不是首选,也没有解决方案。我以为我看到您可以使用(数组)列表代替我现在使用的字符串数组。如果这是真的,请您解释一下如何做到这一点。以及如何随机访问。以及如何将随机访问的答案与为用户显示的问题相匹配?我读了一些关于为此使用类的信息?Hashmap在 Java 中使用以下示例。public class QuestionAnswers {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; HashMap<String, String> questionSets = new HashMap<String, String>();&nbsp; &nbsp; questionSets.put("Question1", "Answer1");&nbsp; &nbsp; questionSets.put("Question2", "Answer2");&nbsp; &nbsp; questionSets.put("Question3", "Answer3");&nbsp; &nbsp; questionSets.put("Question4", "Answer4");&nbsp; &nbsp; questionSets.put("Question5", "Answer5");&nbsp; &nbsp; List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(questionSets.entrySet());&nbsp; &nbsp; System.out.println("************ Questions ************");&nbsp; &nbsp; Collections.shuffle(list);&nbsp; &nbsp; for (Map.Entry<String, String> entry : list) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.getKey());&nbsp; &nbsp; &nbsp; &nbsp; // Here entry.getKey() is Question and if user enters the correct answer&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // match that answer with like -> "user_answer".equals(entry.getValue());&nbsp; &nbsp; }&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答