随机图像显示测验

时间:2017-03-11 12:38:33

标签: java netbeans

我一直在研究带有netbeans的java,制作一个程序,在屏幕上随机显示问题(png图像)约1分钟。当图像闪烁显示时,用户有时间选择他的答案(4个选项中有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. 如何为每个问题分配答案(以便我可以使用if条件)

1 个答案:

答案 0 :(得分: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());
}