首页 > 解决方案 > 我的第一个代码问题!学习 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");
            
        }
    }
}

标签: javaarraysmethods

解决方案


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].


推荐阅读