2017-03-11 66 views
-1

我一直在與NetBeans的Java工作,使一個程序,它顯示問題(PNG圖像)隨機在屏幕上約1分鐘。當圖像閃爍顯示時,用戶有時間選擇他的答案(4個選項中的任意一個)。我的代碼是:隨機圖片顯示測驗

public class NewJFrame extends javax.swing.JFrame { 

/** 
* Creates new form NewJFrame 
*/ 
private String[] images = {"a0.jpg","a1.jpg","a2.jpg","a3.jpg","a4.jpg","a5.png","a6.png"}; 
private int rand; 
public NewJFrame() { 
    initComponents(); 
    Timer time = new Timer(); 
    TimerTask image = new TimerTask(){ 
     @Override 
     public void run(){ 
      Random gen = new Random(); 
      rand = gen.nextInt(6); 
      String image = images[rand]; 
      jLabel1.setIcon(new ImageIcon("src\\images\\" + image)); 
      jLabel1.repaint(); 
      System.out.println(rand); 

     } 
    }; 
    time.schedule(image,100,900); 

} 

一切都做得正確,但下面的問題有:

  1. 重複的問題,
  2. 如何回答分配給每一個問題(這樣我可以,如果條件中使用)
+0

創建一個'Question'和'Answer'類,並從那裏開始 –

+0

您對Random類的使用對我來說看起來不正確。它需要成爲一名班員,而不是該方法的一部分。如果你想阻止某人看到相同的測驗,那麼你必須不止一次地跟蹤他們所看到的內容。您沒有指明用戶如何與圖像交互以提供答案。 – duffymo

+0

歡迎來到Stack Overflow!看起來你可能會問作業幫助。雖然我們本身沒有任何問題,但請觀察這些[應做和不應該](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),並相應地編輯您的問題。 (即使這不是作業,也請考慮建議。) –

回答

0

我會做這樣的:

有問題作爲一個鍵地圖並將答案作爲價值。您可以使用簡單的Map<String, String>來完成此操作,也可以根據您的需要構建自己的問答對象。

爲了避免兩次獲取相同的問題,只需將其從地圖中移出,然後將其顯示給用戶。

Map<String, String> questions = new HashMap<>(); 

// Constructor where we put all the questions into the Map 
public Main() { 
    questions.put("What's 1 + 1?", "2"); 
    questions.put("What's the meaning of life?", "42"); 
} 

public void printQuestion() { 
    Random random = new Random(); 
    Map.Entry<String, String> question = (Map.Entry<String, String>) questions.entrySet().toArray()[random.nextInt(questions.size())]; 
    System.out.println("Question: " + question.getKey()); 
    System.out.println("Answer: " + question.getValue()); 
    questions.remove(question.getKey()); 
}