英文:
How to get they key and value of a LinkedHashMap randomly?
问题
我正在尝试编写一个小型词汇测试。LinkedHashMap vocabulary
包含了词汇。键是一个法语单词,值是一个英语单词。我已经有了一个图形用户界面(GUI),但我在努力从词汇中获取一个随机的法语单词及其位置,以判断输入的单词是否正确。我尝试过使用 ArrayList,但那样我只能获得值,我还需要键来显示要翻译的是哪个单词。任何帮助都将不胜感激。
LinkedHashMap<String, String> vocabulary = new LinkedHashMap<String, String>();
Random random = new Random();
int number = random.nextInt(ReadExcelFile.lastRowNumber);
String value = (new ArrayList<String>(vocabulary.values())).get(number);
英文:
I'm trying to write a little vocabulary test. The LinkedHashMap vocabulary
consists of vocabulary. They key is a french word and the value is an english word. I already have a GUI but I'm struggling to get a random french word from the vocabulary and its position to find out if the entered word is right. I tried to do it with an ArrayList but then I only get the value but I also need the key to show which word the person has to translate. Any help is appreciated.
LinkedHashMap<String, String> vocabulary = new LinkedHashMap<String, String>();
Random random = new Random();
int number = random.nextInt(ReadExcelFile.lastRowNumber);
String value = (new ArrayList<String>(vocabulary.values())).get(number);
答案1
得分: 9
把keys放进一个列表中,然后随机选择一个:
// 在加载(或更改)后执行一次
List<String> keyList = new ArrayList<>(vocabulary.keySet());
Random random = new Random();
int number = random.nextInt(vocabulary.size());
String key = keyList.get(number);
String value = vocabulary.get(key);
英文:
Put the keys into a list, then pick a random one:
// Do once after loading (or changing)
List<String> keyList = new ArrayList<>(vocabulary.keySet());
Random random = new Random();
int number = random.nextInt(vocabulary.size());
String key = keyList.get(number);
String value = vocabulary.get(key);
答案2
得分: 2
你可以按照以下方式进行!
Map<String, String> myMap = new LinkedHashMap<String, String>();
myMap.put("Bonjour", "Hello");
myMap.put("moi", "me");
myMap.put("tue", "you");
List<String> val = new ArrayList<String>(myMap.values());
int randomIndex = new Random().nextInt(val.size());
String randomValue = val.get(randomIndex);
System.out.println(randomValue);
英文:
You can go in the following way!
Map<String, String> myMap = new LinkedHashMap<String, String>();
myMap.put("Bonjour", "Hello");
myMap.put("moi", "me");
myMap.put("tue", "you");
List<String> val = new ArrayList<String>(myMap.values());
int randomIndex = new Random().nextInt(val.size());
String randomValue = val.get(randomIndex);
System.out.println(randomValue);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论