简体   繁体   English

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

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

What I currently have: There are red lines (errors) under the method fillArray and with its above if statement. 我目前拥有的内容:方法fillArray下及其上面的if语句有红线(错误)。 Purpose is to create an array which will start with a button click and fill the array with random int ranging from 0 to 100 目的是创建一个以单击按钮开始的数组,并使用介于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);

watch the brackets '{' '}' I think you are missing one under actionPerformed , BigArray , and createGUI() . 观看方括号'{''}',我认为您在actionPerformedBigArraycreateGUI()下缺少一个。

It can be helpful to code like this: 编写如下代码可能会有所帮助:

class myClass
{
    int myInt;

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

Each closing brace is below the starting brace. 每个右括号都在起始括号下方。

The argument that you can pass to the constructor of Random is the seed , not the range of the generated values. 可以传递给Random的构造函数的参数是seed ,而不是生成值的范围。 (The seed is some kind of initial value; if always use the same seed , the random generator will always generate the same number sequence). 种子是某种初始值;如果始终使用相同的种子 ,则随机数生成器将始终生成相同的数字序列)。

If you want to get a random number within a certain range, use the method random.nextInt(int) instead: 如果要获取一定范围内的随机数,请改用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