繁体   English   中英

如何用随机整数填充数组并创建一个按钮来激活它

[英]How to fill an array with random integers and create a button to activate it

我目前拥有的内容:方法fillArray下及其上面的if语句有红线(错误)。 目的是创建一个以单击按钮开始的数组,并使用介于0到100之间的随机整数填充该数组

import java.awt.*;        //imports data from library
import java.awt.event.*;
import javax.swing.*;

public class FinalArray extends JFrame implements ActionListener {

    private JButton fill, 
    private JTextArea output;

    public static void main(String[] args) { //creates window

    FinalArray demo = new FinalArray();
    demo.setSize(400,450);
    demo.createGUI();
    demo.setVisible(true);
  }
private void createGUI() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new FlowLayout());

    fill = new JButton("fill");//creates button
    window.add(fill);               //and text area
    fill.addActionListener(this);

public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();

    if (source == fill) {
        BigArray.fill();
    }

class BigArray {
    private int [] array;

    public void fillArray() {
        for(int i = 0; i < array.length; i++) {
            array.fill(array[i]=0);
        }
        Random = new Random(101);

观看方括号'{''}',我认为您在actionPerformedBigArraycreateGUI()下缺少一个。

编写如下代码可能会有所帮助:

class myClass
{
    int myInt;

    public void setInt(int myInt)
    {
        this.myInt = myInt;
    }
}

每个右括号都在起始括号下方。

可以传递给Random的构造函数的参数是seed ,而不是生成值的范围。 种子是某种初始值;如果始终使用相同的种子 ,则随机数生成器将始终生成相同的数字序列)。

如果要获取一定范围内的随机数,请改用random.nextInt(int)方法:

int a = random.nextInt(101); // returns a random value between 0 and 100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM