+ 1

Comparing the indexes of two arrays in Java

Hi all! I need help with a simple coding challenge. I am comparing two arrays but my code doesn't work the way it suppose to. Code should return 1 if the indexes are the same, otherwise -1, in a new array. Here is an example: Inputs: User-typed Array: ["cat", "blue", "skt", "umbrells", "paddy"] Correct Array: ["cat", "blue", "sky", "umbrella", "paddy"] Output: [1, 1, -1, -1, 1] My code returns all -1s. Can't figure out what is the issue. Thanks in advance! Here is my code: public class Challenge { public static int[] correctStream(String[] user, String[] correct) { int[] output = new int[user.length]; for (int i = 0; i < user.length; i++){ for(int j = 0; j < correct.length; j++){ if (user[i].equals(correct[j])){ output[i] = 1; } else{ output[i] = -1; } } }return output; } }

8th Jul 2020, 7:18 PM
GG128
6 Answers
+ 3
Emanuel Maliaño when comparing String values in Java you need to use the equals() method. The use of the comparison operator "==" will only return true if they are the same object in memory which is not guaranteed even with a direct comparison of literal Strings. The equals() method will compare the values of the object (in the case of String objects) and only return true if they match.
8th Jul 2020, 7:46 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
First you should ensure that both arrays are of the same length. Second you don't need a second loop for this task. You can just iterate over both with the same index i and compare the values at exactly this point. If you're comparing each element at index one in first array with each index two in the other array, you'll get completely another result.
8th Jul 2020, 7:23 PM
Sandra Meyer
Sandra Meyer - avatar
+ 1
Hi. You should not use second "for", only first and one index.
8th Jul 2020, 8:03 PM
Egor
0
You do not need to use equal instead of that you can use the comparison operator
8th Jul 2020, 7:29 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
0
GE12 With that code, just add i==j as if(user[i]. equals(correct[j]) && i==j) But you can that with single loop also, if you need same indexes only...
8th Jul 2020, 7:57 PM
Jayakrishna 🇼🇳
0
Thanks all for your responses! Using single for loop and changing variable j to i worked : )
8th Jul 2020, 8:59 PM
GG128