今天我的老师让我为他编写一个随机的演示主题选择器 .
这个想法是,学生去电脑并点击消息Dialog,然后随机生成1到主题的最大索引之间的数字,然后打印相应的主题 .
我用HashMaps尝试过 . 将与String保持在一起的键放在一起,这样我就可以(在输出之后)删除该条目,这样其他学生就无法获得相同的主题 .
但它始终返回至少1个空引用 - > null .
这是代码:
static HashMap<Integer, String> map = new HashMap<>();
public static void main(String[] args){
int anzahlEintraege = Integer.parseInt(JOptionPane.showInputDialog("Wie viele Themen gibt es?"));
for(int i = 0; i < anzahlEintraege; i++){
map.put((i+1),JOptionPane.showInputDialog("Geben Sie das Thema Nummer " + (i+1) + " ein!"));
}
JOptionPane.showMessageDialog(null, "Jetzt geht's Los!");
int max = map.size();
int removed = 0;
for(int i = 0; i < max; i++){
Random r = new Random();
int random = r.nextInt(max-1)+1;
JOptionPane.showMessageDialog(null, "Sie haben das Thema "+ map.get(random) + " gezogen!");
map.remove(random);
removed++;
}
}
1 回答
您遇到的问题是您可以多次选择相同的随机数,即使您已经使用该键删除了该元素 .
您最好只创建一个密钥列表,随机化它们的顺序,然后简单地迭代它们,而不是尝试选择非重复的随机数 .
这是一个使用您应该能够适应的字符串的简单示例: