[英]How to randomly get item from string array?
I am trying to generate random questions from my String array called Questions. 我试图从我的String数组中生成随机问题,称为Questions。 There 10 items inside.
里面有10个物品。 I am trying to set the text of JLabel where once the button is click one of the questions from the array will randomly be selected and displayed.
我试图设置JLabel的文本,单击该按钮后,将随机选择并显示数组中的一个问题。 However these 2 sections of code doesn't return anyting.
但是,这两段代码不会返回任何内容。
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]);
Don't hardcode the magic number 10
in getNextQuestion()
. 不要在
getNextQuestion()
硬编码魔术数字10
。 I would prefer ThreadLocalRandom
over Math.random()
. 与
Math.random()
我更喜欢ThreadLocalRandom
。 Like, 喜欢,
public String getNextQuestion() {
return Questions[ThreadLocalRandom.current().nextInt(Questions.length)];
}
Then invoke that method in actionPerformed
like, 然后在
actionPerformed
调用该方法,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Button) {
Hello.setText(getNextQuestion());
}
}
You should be calling your method getNextQuestion 您应该调用您的方法getNextQuestion
OK, you need an actionlistener on your button in order for something to happen. 好的,您需要在按钮上添加一个动作侦听器,以便进行某些操作。 Something like
就像是
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());
}
});
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.