1st Aug 2020, 5:19 PM
Yahel
Yahel - avatar
10 Answers
+ 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.
1st Aug 2020, 5:28 PM
Sandra Meyer
Sandra Meyer - avatar
+ 3
if (arr[i].equals(arr[j])){ checkForDups++; }
1st Aug 2020, 5:28 PM
Aayush $aini
Aayush $aini - avatar
+ 3
Basically you missed to skip i == j
1st Aug 2020, 5:44 PM
Sandra Meyer
Sandra Meyer - avatar
+ 3
Sandra Meyer thanks!!!
1st Aug 2020, 5:51 PM
Yahel
Yahel - avatar
+ 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; } }
1st Aug 2020, 5:36 PM
Yahel
Yahel - avatar
+ 2
I'll make a clean version of that for you, please wait 😉⏳
1st Aug 2020, 5:37 PM
Sandra Meyer
Sandra Meyer - avatar
1st Aug 2020, 5:44 PM
Sandra Meyer
Sandra Meyer - avatar
+ 2
And another point, since you're in fact counting all duplicates twice: Divide your count afterwards! 😉 return value / 2;
1st Aug 2020, 5:46 PM
Sandra Meyer
Sandra Meyer - avatar
+ 2
wow, ok. thanks! but what does this part do: i!=j ?
1st Aug 2020, 5:49 PM
Yahel
Yahel - avatar
+ 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!
1st Aug 2020, 5:50 PM
Sandra Meyer
Sandra Meyer - avatar