user1710971
user1710971

Reputation: 1

How to display the amount of negative numbers in an array?

How to display the amount of negative numbers in an array?

This is what I have so far:

public static void main(String args[]){
    int arrayNumbers[] = { 3, 4, 7, -3, -2};
    for (int i = 0; i <= arrayNumbers.length; i++){
        int negativeCount = 0;
        if (arrayNumbers[i] >= 0){
                negativeCount++;
    }
    System.out.println(negativeCount);
    }
}

}

Upvotes: 0

Views: 2806

Answers (3)

Priyank Patel
Priyank Patel

Reputation: 6996

You were making negativeCount variable back to 0 everytime you found a negative number and also you need to check if arrayNumbers[i]<0

    public static void main(String args[])
     {
            int arrayNumbers[] = { 3, 4, 7, -3, -2};
            int negativeCount = 0;
            for (int i = 0; i <= arrayNumbers.length; i++)
            {

              if (arrayNumbers[i] < 0)
               {
                 negativeCount++;
               }

            }

             System.out.println(negativeCount);
      }

        }

Upvotes: 0

Sweebo
Sweebo

Reputation: 336

you need to do the following;

1) declare the variable negativeCount outside the loop.

2) change the of statememt's condition to less than 0 and not greater or equal. (or u can just add a not operator infront of the current condition.

Upvotes: 0

shinkou
shinkou

Reputation: 5154

You almost have it, but you keep reinitializing the counter. Take int negativeCount = 0; out and put it before the loop.

EDIT As another user has mentioned in the comment, you are counting positive numbers instead of negative ones. So, fix the if (arrayNumbers[i] >= 0) also.

Upvotes: 2

Related Questions