我开发了基诺游戏,我对如何从控制台获取随机数并将它们放到文本字段感到困惑。我尝试用ArrayList或Array制作它,但它错了。 您可以在下面找到我的代码。 谢谢你的帮助!!
import java.util.Random;
public class Game {
private final int RANDOMNUMBER = 80;
private int prob;
String k;
String res;
public void rNumbers() {
for (int x = 0; x <= 12; x++) {
Random d = new Random();
prob = d.nextInt(RANDOMNUMBER) + 0;
System.out.println(prob);
}
k= Integer.toString(prob);
}
public String toString(){
return ""+prob;
}
}
另一个班级
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GuiKino extends JFrame implements ActionListener {
private JPanel mainPanel;
private JPanel contentPanel;
private JPanel otherPanel;
private JTextField text;
private JButton rollButton;
Game t = new Game();
private JLabel[] a = new JLabel[80];
GridLayout gridLayout = new GridLayout();
public GuiKino() {
this.setTitle("Kino");
// Create panels
mainPanel = new JPanel();
contentPanel = new JPanel();
otherPanel = new JPanel();
this.contentPanel = (JPanel) getContentPane();
contentPanel.add(otherPanel, BorderLayout.SOUTH);
contentPanel.add(mainPanel, BorderLayout.CENTER);
mainPanel.setLayout(new GridLayout(10, 10));
otherPanel.setLayout(new GridLayout(1, 4));
text = new JTextField("");
rollButton = new JButton("Klirosi");
rollButton.addActionListener(this);
otherPanel.add(text);
otherPanel.add(rollButton);
for (int j = 0; j < a.length; j++) {
a[j] = new JLabel("");
a[j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
//cell numbers
for(int l=0; l<a.length; l++){
a[l].setText(""+l);
}
for (int i = 0; i < a.length; i++) {
mainPanel.add(a[i]);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == rollButton) {
t.rNumbers();
text.setText(t.toString());
text.getText();
}
}
}
答案 0 :(得分:0)
尝试使用Math类See the docs here中的random()方法获取随机数。
我希望我曾帮助过你。
的Pd。对不起我的英语我是委内瑞拉。
答案 1 :(得分:0)
您可以使用ThreadLocalRandom.current().nextInt(origin, bound);
获取某个范围内的随机数,原点是包含的底部数字,并且绑定是独占的上限数字。
答案 2 :(得分:0)
伙计们我找到了解决方案。我在我的游戏类中创建了一个新的变量StringBuilder sb = new StringBuilder();
,然后我将sb.append("-");
和sb.append(prob);
用于我的方法rNumbers()
并且工作了!