+ 3
why isnt it working?
10 Respostas
+ 3
You also compare same elements with each other (e.g. index 0 with index 0). Btw. you should take a look at foreach-loop in Java, use the equals-method to compare strings, and rename the method to countDuplicates. And remove the unnecessary and totally wrong inner third loop.
+ 3
if (arr[i].equals(arr[j])){
checkForDups++;
}
+ 3
Basically you missed to skip i == j
+ 3
Sandra Meyer thanks!!!
+ 2
Sandra Meyer , whats the problem now?
code:
import java.util.*;
public class Main
{
public static void main (String[] args){
final String[] myArr = {"banana" , "apple" , "apple"};
countDuplicates(myArr);
}
public static int countDuplicates(final String[] arr){
int checkForDups = 0;
for (int i = 0; i < arr.length; i++){ //this loop is for going through the array
for (int j = 0; j < arr.length; j++){ //this one also... ^
if (arr[i].equals(arr[j])){
checkForDups++;
}
}
}
return checkForDups;
}
}
+ 2
I'll make a clean version of that for you, please wait 😉⏳
+ 2
And another point, since you're in fact counting all duplicates twice: Divide your count afterwards! 😉
return value / 2;
+ 2
wow, ok. thanks! but what does this part do: i!=j
?
+ 2
Well, if you have { "banana", "apple" } and then compare arr[0] with arr[0], then you'll find, that banana == banana, but this is not, what you want to count!