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

标签 java android arrays methods random

我目前所拥有的:在方法 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);

最佳答案

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

如果你想获得一定范围内的随机数,请使用random.nextInt(int)方法:

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

关于java - 如何用随机整数填充数组并创建一个按钮来激活它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337253/

相关文章:

java - GWT:如何滚动到页面底部?

android - 以编程方式更改 ActionBar 图标

android - 在 Android 中更改布局的背景颜色

javascript - 在 PHP 函数上使用 Javascript 数组,无论是在同一个文件上还是与其他函数一起在另一个文件上

java - Java中的序列化对象大小与内存对象大小

java - Android摆脱DialogFragment float 边距

java - Spring boot - Thymeleaf 与 JQuery?

java - android在异步任务中更新自定义 View

Javascript - Chrome 控制台 - "Array(0)"是什么意思?

javascript - 如何从javascript数组中推送JSON中的元素