My first code question! Learning Java and need help performing basic stats on an array

Viewed 60

This project is all about methods and arrays and breaks down into 3 parts. Firstly, create an array. Second, fill said array with random ints. Lastly, create a method that displays whether each int is even or odd as well as provides the average of the random ints. Java is my first programming language that i'm being introduced to in my curriculum and I've worked in this issue for about 4-5 hours now but hit a wall. I can't seem to get my statsDisplay method to perform the necessary stats on my created arrays. It appears that since it always results with alternating "even/odd", it's just creating its own array from 1-20 and analyzing that instead of the previous Math.random() array. Is anyone able to see what might be going wrong here? Also, this is my first ever post on here so I'm sorry if it's not formatted correctly or asked in an odd way...

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");
            
        }
    }
}
1 Answers

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

Related