+ 2
I have the following java code and I need help in a for loop that searches in an array for a certain element
I have this code. It won t work in Sololearn console and it requires multiple inputs, so please check it in your console (jdk) I have a list of things i can do: 0 exit 1 create student 2 check if there are any students in the class whose nrMatricol is equal with the user's input The problem is at 2. I search for an nrMatricol (example "22222") and enter. the "for" loop goes on and i get 19 "no"'s, because there are 19 null elements. But, even if "22222" exists (which does, because there are 5 existing students), nothing gets written (line 94). Help pls, am I writing something wrong? I think i did all the conversions to string. https://code.sololearn.com/c6Icu2iuHb4g
6 Respostas
+ 5
🍇 Alex Tușinean 💜
Don't compare string with ==
use equals method
if((AIA.lista_studenti[k].getNrMatricol()).equals(nrMatricolCautat))
+ 2
🍇 Alex Tușinean 💜
I think Tapabrata Banerjee [Less Active] explained well.
+ 1
Wait, but what is == used for in java? I though == is for comparison
anyway, your solution works. Thanks a lot! I would have never guessed the == was the issue.
+ 1
🍇 Alex Tușinean 💜
== compares value as well as reference so in Java String is a reference type so two String cannot have same reference that's why == is not preferable for String comparison.
1, 2, 3 are value type so that is not wrong.
0
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ does that mean that where I compared selectie with 0 1 and 2 is also wrong?