【问题标题】:Random Presentation Topic Picker returns null随机演示主题选择器返回 null
【发布时间】:2017-06-20 04:13:23
【问题描述】:

今天我的老师让我为他编写一个随机演示主题选择器。

这个想法是,学生去电脑并点击消息对话框,然后随机生成一个介于 1 和主题最大索引之间的数字,然后打印相应的主题。

我用 HashMaps 试过了。将与字符串保持在一起的键放在一起,以便我可以(在输出之后)删除该条目,这样其他学生就无法获得相同的主题。

但它总是返回至少 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++;

    }
}

【问题讨论】:

  • 不要随意删除。当它再次被随机选择时,你的地图中没有它的项目,所以你有 null。

标签: java random generator


【解决方案1】:

您遇到的问题是您可以多次选择同一个随机数,即使您已经使用该键删除了元素。

与其尝试选择不重复的随机数,不如简单地创建一个密钥列表,随机化它们的顺序,然后简单地迭代它们。

这是一个使用字符串的简单示例,您应该能够适应:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Scratch {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "foo");
        map.put(2, "bar");
        map.put(3, "baz");

        List<Integer> keys = new ArrayList<>(map.keySet());
        Collections.shuffle(keys);

        for (Integer key : keys) {
            String randomValue = map.get(key);
            System.out.println(randomValue);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2021-12-25
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多