【问题标题】:Picking and displaying data randomly from an array从数组中随机选择和显示数据
【发布时间】:2015-04-20 20:35:49
【问题描述】:

我创建了一个包含 100 个元素的数组,我想知道如何随机选择数组中的一个元素并显示其中包含的结果。

import java.util.ArrayList;
import java.util.Random;

public class slotMachine {

  Symbol[] slot1, slot2, slot3;

  public slotMachine() {
    // Generate a random element and state what it is
  }

  public void initSlots() {
    int i;
    //Slot 1
    slot1 = new Symbol[100];
    for (i = 0; i < 30; i++) {
      slot1[i] = Symbol.Bar;
    }
    for (; i < 60; i++) {
      slot1[i] = Symbol.Cherry;
    }
    for (; i < 80; i++) {
      slot1[i] = Symbol.Lime;
    }
    for (; i < 100; i++) {
      slot1[i] = Symbol.Seven;
    }
  }
}

【问题讨论】:

标签: java arrays random


【解决方案1】:

Math.random() 是您的答案。您可以将以下方法添加到您的课程中:

private int randomElement(Symbol[] array)
{
    int index = (int)(Math.random() * array.length);
    return array[index];
}

如果您想获得均匀分布的随机整数,请查看Random.nextInt()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多