【问题标题】:Basic Java Array and For Loop基本 Java 数组和 For 循环
【发布时间】:2019-01-31 18:31:22
【问题描述】:

我正在学习 Java 课程并且一遍又一遍地阅读相同的解释,我只是想确保我正确理解它。

他们提供的课程中的示例是掷骰子游戏,他们想查看每个数字的掷骰频率。

我不确定的代码 sn-p 是这样的:

for(int roll = 1; roll < 1000; roll++){
    ++freq[1+rand.nextInt(6)];
}

这部分我明白了:1+rand.nextInt(6)

但我不明白这部分:++freq 以及它如何计算结果

我将其理解为(以我掷出 4 的示例为例):

for(int roll = 1; roll < 1000; roll++){
    ++freq[4];
    //all indexes in freq are == 0 to start
    //freq[4] is index 4 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], freq[5], and freq[6] are all still == to 0
}

for(int roll = 1; roll < 1000; roll++){
    ++freq[6];
    //freq[6] is index 6 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], and freq[5] are all still == to 0
    //freq[4] and freq[6] are both == to 1
}

这对吗?

【问题讨论】:

  • ++freq[4]freq[4] = freq[4] + 1 的缩写
  • 为了记录,++freq[1+rand.nextInt(6)]; 是相当不清楚的代码。除非你是在 2 英寸的屏幕上开发,或者因为编写更多代码行而受到惩罚,否则将其写为变量 int roll = 1 + rand.nextInt(6); 和增量 ++freq[roll]; 会更清晰。

标签: java arrays for-loop random


【解决方案1】:
int[] freq = new int[7];

    for(int roll = 1; roll < 1000; roll++){
        ++freq[1+rand.nextInt(6)];
    }

在上面的代码中rand.nextInt(6)返回一个从0到5的值,用于访问数组freq的相关整数值

++freq 部分将访问的整数值增加 1。

示例: 如果rand.nextInt(6) 返回2

freq[1 + 2] = freq[1 + 2] + 1;

但是,从 1 + rand.nextInt(6) 开始,永远不会产生 0。因此,freq 数组的第一个元素应该被忽略。

freq[n] 会给你nth 脸的频率。

【讨论】:

  • 这是一个非常有用的细分。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2014-06-22
相关资源
最近更新 更多