Your algorithm has some problems. The first is as follows:
String [] lista1 = new String [];
When you create the array, you must specify the length of the array. Something like this:
String[] lista1 = new String[10];
However, you can say that 10 is a lot ... or maybe a little ... or maybe you should ask the user how many they are. Incidentally, you are not asking the user to type anything, you are just writing on the console without reading anything from there.
Thus, to read a number from the console:
System.out.print("Escreva quantos nomes há na primeira lista: ");
int tamanhoLista1 = sc.nextInt();
With this you can create the arrays:
String[] lista1 = new String[tamanhoLista1];
And so, you do the same with list 2. The statement of your exercise does not make it clear whether the two lists necessarily have the same size or not. But if they have not, you can make the size list 1 be different from the size of list 2.
The names are also missing. To read a name, you can do this:
String nome = sc.nextLine();
Or, read directly into the array:
nome[i] = sc.nextLine();
And in the case above, you might want to know where this i
comes from. The answer is that you will need to read each of the name lists using a for
and this i
will be the index variable of that for
.
Already when comparing the lists, you are comparing the element 0 of a list with 0 of another list. The 1 from a list with 1 from the other list. The 2 from a list with 2 from the other list ... But that's not what you want! For example, imagine this case:
List 1: Alberto, Fernanda, Marcelo, Rodrigo, Maria, Tatiana
List 2: Joaquim, Carlos, Maria, Adriana, Fernanda, Marcelo, Alberto
How many names in list 1 are in list 2? The correct answer is 4 (Alberto, Fernanda, Marcelo and Maria). But your algorithm will not find any of those names because their positions do not match.
To address this, I recommend taking a different approach. You will need to create two for
bonds within one another. The one outside goes through list 1 and the one inside goes through list 2, so as to compare all the elements of a list with all the elements of the other list. When you find an element that matches, you make cont++;
and give break;
. The break;
is important, because once the list 1 element is found, you will not want to keep looking (and if you continue, you will have a problem with lists that have repeated elements).
Finally, one last detail:
return cont/lista2.length;
Here cont
is integer and lista2.length
is also integer. Therefore, an entire division will be carried out. Only after the integer division is made will the value be converted to a double
to be returned. This is not what you want either, but the solution is easy:
return ((double) cont) / lista2.length;
This will give you a number between 0 and 1. As you want percent, multiply by 100:
return ((double) (cont * 100)) / lista2.length;