Reputation:
I am trying to follow the book which we are given at the University but count variable is not being incremented despite condition is true ... What am I missing here would like to mention I am new to Java
public static void main(String[] args) {
int[] list = new int [] {1, 3, 4, 5, 7, 8, 9, 11, 14};
int count = 0;
for(int i = 0; i < list.length -1; i ++){
if(list[i] == list[i+1])
count ++;
}
}
Upvotes: 1
Views: 117
Reputation: 2276
if(list[i] == list[i+1])
will always be false. Look at the list; there are no two adjacent values that are equal to each other, which is what your if
is testing. So count
will always stay 0.
Upvotes: 3
Reputation: 2129
count++; is part of the if wich is always false
your code is equal to :
if(list[i] == list[i+1]){
count ++;
}
list[i] is always different to list[i+1] 1!=3 3!=4 4!=5 .....
if you want to count you have to put count++ outside the is. And i recommend to always put bracket to if and while to avoid this type of mistake
Upvotes: 3