为了账号安全,请及时绑定邮箱和手机立即绑定

随机访问字符串数组

随机访问字符串数组

海绵宝宝撒 2021-08-25 09:52:18
我想将 ( .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以及如何将随机访问的答案与为用户显示的问题相匹配?我读了一些关于为此使用类的信息?提前致谢!编辑:我只是想为每个问题和答案创建一个数组,然后以一种或其他方式访问它们?
查看完整描述

2 回答

?
Helenr

TA贡献1780条经验 获得超4个赞

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


由于您想更改测验/随机等问题,建议您将问题和答案映射在一起。洗牌问题列表和答案列表不是首选,也没有解决方案。


我以为我看到您可以使用(数组)列表代替我现在使用的字符串数组。如果这是真的,请您解释一下如何做到这一点。以及如何随机访问。


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


Hashmap在 Java 中使用以下示例。


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());

    }

  }

}


查看完整回答
反对 回复 2021-08-25
  • 2 回答
  • 0 关注
  • 203 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号