首页 文章

如何从字符串数组中随机获取项目?

提问于
浏览
0

我试图从我的String数组中生成一个名为Questions的随机问题 . 里面有10件物品 . 我正在尝试设置JLabel的文本,一旦按钮单击,将随机选择并显示数组中的一个问题 . 但是这两段代码不会返回任何内容 .

public String getNextQuestion() {
    int NextQues = (int)(Math.random()*10);
    return Questions[NextQues];}

public void actionPerformed (ActionEvent e) {
     if(e.getSource() == Button) {  
Hello.setText(Questions[NextQues]);

2 回答

  • 0

    请勿在 getNextQuestion() 中对幻数 10 进行硬编码 . 我更喜欢 ThreadLocalRandom 而不是 Math.random() . 喜欢,

    public String getNextQuestion() {
        return Questions[ThreadLocalRandom.current().nextInt(Questions.length)];
    }
    

    然后在 actionPerformed 中调用该方法,

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == Button) {
            Hello.setText(getNextQuestion());
        }
    }
    
  • 0

    你应该调用你的方法getNextQuestion

    好的,您需要在按钮上使用actionlistener才能实现某些功能 . 就像是

    public String getNextQuestion() {
                int NextQues = (int)(Math.random()*10);
                return Questions[NextQues];}
    
    
    // inside main method 
    ...    
        Button.addActionListener (
                 new ActionListener()
                 { 
                    public void actionPerformed(ActionEvent e)
                    {
                       Hello.setText(getNextQuestion());
                    }
                 });
     ...
    

相关问题