使用 java.util.Random 在游戏中随机写入数字

这是我的代码。


我希望窗口看起来像这样,但我不喜欢在这段代码中将数字写成 1-36。当我删除该代码并尝试:


Random r = new Random();

for(int k = 0; k < z; k++) {

并且我定义z=20;了最初带有 1-36 号的字段被删除。我的预期输出是,像下面的代码一样的字段,但每次打开游戏时数字都会有所不同。


JFrame frame = new JFrame();

frame.setSize(600, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new GridLayout(1, 2, 1, 1));


JPanel panel = new JPanel();

panel.setLayout(new GridLayout(2, 1, 1, 1));


frame.add(panel, BorderLayout.CENTER);


JPanel center = new JPanel();

center.setLayout(new GridLayout(9, 9, 1, 1));

int z = 0;

for(int i = 0; i < 6; i++) {

    for(int j = 0; j < 6; j++) {


        JButton button = new JButton(Integer.toString(++z));

        center.add(button);

    }

}

frame.add(center, BorderLayout.CENTER);

frame.setVisible(true);


慕侠2389804
浏览 102回答 1
1回答

阿波罗的战车

您可以使用一种方法,将指定范围内的随机数添加为按钮的名称。像这样:public class Frame {public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; JFrame frame = new JFrame();&nbsp; &nbsp; frame.setSize(600, 400);&nbsp; &nbsp; frame.setVisible(true);&nbsp; &nbsp; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);&nbsp; &nbsp; frame.getContentPane().setLayout(new GridLayout(1, 2, 1, 1));&nbsp; &nbsp; JPanel panel = new JPanel();&nbsp; &nbsp; panel.setLayout(new GridLayout(2, 1, 1, 1));&nbsp; &nbsp; frame.add(panel, BorderLayout.CENTER);&nbsp; &nbsp; JPanel center = new JPanel();&nbsp; &nbsp; center.setLayout(new GridLayout(9, 9, 1, 1));&nbsp; &nbsp; for(int i = 0; i < 6; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j < 6; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JButton button = new JButton(Integer.toString(random(1, 6)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; center.add(button);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; frame.add(center, BorderLayout.CENTER);&nbsp; &nbsp; frame.setVisible(true);}private static int random(int min, int max) {&nbsp; &nbsp; return (int) (Math.random() * (max - min) + min);&nbsp; &nbsp; &nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java