java - 我的第一个代码问题!学习 Java 并需要帮助对数组执行基本统计信息
问题描述
这个项目是关于方法和数组的,分为 3 个部分。首先,创建一个数组。其次,用随机整数填充所述数组。最后,创建一个方法来显示每个 int 是偶数还是奇数,并提供随机 int 的平均值。Java 是我在课程中被介绍的第一种编程语言,我已经在这个问题上工作了大约 4-5 个小时,但碰壁了。我似乎无法让我的 statsDisplay 方法在我创建的数组上执行必要的统计信息。似乎因为它总是以交替的“偶数/奇数”产生结果,所以它只是从 1-20 创建自己的数组并分析它而不是之前的 Math.random() 数组。有没有人能看到这里可能出了什么问题?另外,这是我第一次在这里发帖,如果是的话,我很抱歉'
public class Practicestuff {
public static void main(String[] args) {
int[] vals = new int[20];
fill(vals);
statsDisplay(vals);
print(vals);
}
public static void print(int[] array) {
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
public static void fill(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() *100);
public static void statsDisplay(int[] array) {
for(double i = 0; i < array.length; i++) {
if(i % 2 == 0) {
System.out.println("Number is even");
if(i % 2 != 0)
System.out.println("Number is odd");
}
}
}
解决方案
In your statsDisplay()
method, the i
in the for
loop is the index (1, 2, 3, 4...). The if
statements are checking if i
is odd or even. You want to be checking if array[i]
is odd or even, so you should replace the i
in the if statements with array[i]
.
推荐阅读
- r - 在一个表中汇总来自多个数据帧的相同变量
- nomad - 为什么 nomad 监听 80 端口?
- python - Pandas:转置、分组和汇总列
- ruby-on-rails - 记录的自我参照关系只会与自己建立关系
- css - 使用 Qt 5 为 QDockWidget 设置样式时出现神秘的无样式水平线
- javascript - 如何在Javascript中的特定位置插入百分比
- service-worker - 如何使用 React 配置 Service Worker 以防止在 AWS CloudFront 的新部署中出现未捕获的语法错误
- oracle - 如何从多个表和列中从 Oracle 检索数据而不重复?
- ios - 将 CAGradientLayer 应用于 layer.borderColor
- apache-kafka - 流集:有没有办法使用流集来计算 Kafka 主题中的记录