【问题标题】:Applying Math.random() to call arrays应用 Math.random() 调用数组
【发布时间】:2014-03-12 10:28:27
【问题描述】:

是否可以使用 Math.random() 命令从数组中调用随机行,或者实际上是否有另一种方法?抱歉,如果这有一个明显的答案,但我对编程完全陌生。我的代码如下:

final float line_positions[][] = new float[][] {
        //X coordinate of line, Y Coordinate of hole
}
        { 600, 0.5f },
        { 900, 0.3f },
        { 1200, 0.2f },
        { 1500, 0.3f },
        { 1800, 0.1f },
        { 2100, 0.4f },
        { 2400, 0.5f }

};

......

int temp_score = 0;

for (int i = 0; i < line_positions.length; i++) {

float y = line_positions[i][Y] * ScreenHeight();
float x = ScreenX((int) line_positions[i][X] * ScreenWidth() * 0.0015f);

}

【问题讨论】:

  • 所以你想让你的i被一个随机数替换?但仍然循环检索所有line_positions

标签: java android arrays random


【解决方案1】:

使用随机。

Random rnd = new Random();
int randomRow = rnd.nextInt(line_positions.length);

如果您只希望每一行只显示一次,那么我建议将数组转换为列表,使用 Collections.shuffle() 随机化并遍历列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2010-12-03
    • 2015-08-13
    • 2013-02-25
    • 2018-08-22
    • 2011-08-22
    相关资源
    最近更新 更多