Search code examples
javaarraysfor-loopinteger

Why does my CalcOddIntegers method always return zero?


This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.

        
        System.out.print("Enter length of sequence\n");
        int length = console.nextInt();
        int[] array = new int[length];
        System.out.print("Enter the sequence: \n");
        int count = 0;
        int i = 0;
        for (i = 0; i < length; i++) {
            array[i] = console.nextInt();
        }
        for (i = 0; i < length -1; i++); {
            if (array[i] % 2 != 0) {
                count++;
            }
        }
        System.out.printf("The count of odd integers in the sequence is %d\n", count);
    }

Example of console:

2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit


3
Enter length of sequence
4
Enter the sequence: 
1
2
3
4
The count of odd integers in the sequence is 0

I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.


Solution

  • Remove the semi-colon (;) in the line

    for (i = 0; i < length -1; i++);
    the semi-colon terminates the loop hence an assumption that your line does nothing.