gpt4 book ai didi

java - 更有效的存储值的方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:25:01 25 4
gpt4 key购买 nike

我正在考虑制作一个数学程序。它会从一组问题中随机提出一个问题,然后验证答案。这是我目前所拥有的:

String[] questions = {"3 * 19", "21 * 9", "7 * 4", "349274 * 0", "16 / 2", "3 + 86", "5 - 9"};
int[] answers = {57, 189, 28, 0, 8, 89, -4};

(它通常不是这样间隔的;我这样做只是为了显示哪些答案与什么问题相关)

有没有更有效的方法(我只对存储数据感兴趣,检索它)?

最佳答案

应该这样做:

Map<String,Integer> map = new HashMap<String, Integer>(){{     
put("3 * 19", 57);
put("21 * 9", 189);
put("7 * 4", 28);
put("349274 * 0", 0);
put("16 / 2", 8);
put("3 + 86", 89);
put("5 - 9", -4);
}};

@Bruno Reis 的简短说明:

Just note that this creates an anonymous inner class that inherits from HashMap. Therefore, it has a (non-transient) reference to the instance of the class where it has been created, which might pose problems if you try to serialize the map.

更新:以下是检索随机问题值的方法:

Random generator = new Random();
Object[] values = map.values().toArray();
int randomAns = values[generator.nextInt(value.length)];

关于java - 更有效的存储值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140854/

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