简体   繁体   中英

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. 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

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() .

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. (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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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