I got an ArrayList which consist of 2 type of values: win & loss. I'm trying to count how many times in a row a win have occurred in the ArrayList. I have noget been able to complete the taske so far.
ArrayList <String> wins = new ArrayList<String>();
System.out.print(wins);
//[Won, Won, Won, Loss, Loss, Won, Won, Loss, Loss, Loss, Loss, Loss, Won, Won, Won, Won, Won, Loss]
String value = wins.get(0);
int maxValue=1;
int count = 1 ;
for (int i=1; i<wins.size(); i++){
if(wins.get(i) == wins.get(i-1)){
count++;
if(count >= maxValue){
maxValue = count;
value = wins.get(i);
}
}
}
System.out.println(value + " : " + maxValue );
// Won : 1
The outcome is obviusly wrong as win have occurred 4 times in a row at some point in the ArrayList. Can anyone help me out with this one?
You should try by using equals and not reference ==
equality:
if(wins.get(i) == wins.get(i-1)){
Should be:
if(wins.get(i).equals(wins.get(i-1))) {
Why this could work with String, given that constant are interned, this is not always the case.
Last but not least, you must reset your count when the equality mismatch!
As in:
for (int i=1; i<wins.size(); i++){
String current = wins.get(i);
if (current.equals(wins.get(i-1))) {
count++;
if(count >= maxValue){
maxValue = count;
value = current;
}
} else {
count = 0;
}
}
Note that you probably don't need value
at all.
Thank you. I'm still kinda new but this makes sense. However, I want to ask if you could give me an example of how to reset my counter when I get a mismatch?