【问题标题】:How to fill an array with random integers and create a button to activate it如何用随机整数填充数组并创建一个按钮来激活它
【发布时间】:2013-12-18 16:33:18
【问题描述】:

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

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);

【问题讨论】:

  • fillArray 方法/BigArray 类的其余部分在哪里?

标签: java android arrays methods random


【解决方案1】:

注意括号'{' '}' 我认为您在actionPerformedBigArraycreateGUI() 下缺少一个。

这样编码会很有帮助:

class myClass
{
    int myInt;

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-25
      • 2017-04-21
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      相关资源
      最近更新 更多