0
今天我的老師問我編程爲他隨機提示話題選擇器。隨機演講題目選擇器返回null
的想法是,該學生進入對消息對話框的PC和點擊,然後隨機產生和1之間的數的主題的最大下標,然後打印根據主題。
我HashMaps這樣嘗試過。放入與String保持一致的鍵,這樣我就可以(在輸出之後)刪除該條目,以便其他學生不能獲得相同的主題。
但它始終返回至少1空參考 - >空。
下面是代碼:
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++;
}
}
不要取出隨機的。當它再次被選爲一個隨機數時,你的地圖中沒有它的項目,所以你有空。 –