Help in Java: Arrays

Asked

Viewed 261 times

-3

Exercise:

Make two lists of names in the form of arrays, compare how many names on List 1 are on List 2, and then calculate the percentage of these, about the percentage of total people on List 2.

Follow the code I’ve already made:

import java.util.Scanner;

public class CalourosDoadores {

    public static void main (String args []) {

        System.out.println ("Escreva os Nomes na Primeira Lista: ");

        Scanner sc = new Scanner (System.in);

        String [] lista1 = new String [];

        System.out.println ("Escreva os Nomes na Segunda Lista: ");

        String [] lista2 = new String [];


        System.out.println (calcularLista (lista1, lista2));
    }

        public static double calcularLista(String lista1[], String lista2[]) {

            int cont = 0;

            for (int i = 0; i<lista1.length;i++) {

                if (lista1[i].equals(lista2[i])) {

                    cont++;
                }

            }

            return cont/lista2.length;
        }
}

Please, can someone help me finish?

  • What doubt are you having?

  • It is giving problems in the execution of the Algorithm. At the time of putting the number of names. I wanted to put a while(hasNext()), but I don’t know how to put it, and I don’t know where. ?

  • What problem? Be more specific where it is occurring and what problem is occurring.

  • Please, can you help me to run this Algorithm? It is giving problems that is missing the dimension of the Array. I wanted to put while(hasNext()). And even if you put the dimensions of the Lists, it gives the: java.lang.nullPointerException

  • The error already gave you the solution, inform the dimension of the vector when you start it. Ex.: String[] meuVetor = new String[6] where 6 is the dimension.

  • Even by placing the dimensions, it gives the error of java.lang.nullPointerException. Please, you can help?

  • If you also help me by putting exactly the stack of errors and on which line the error occurs in the question, yes.

  • Right. The IDE says it gives error on this line: if (list1[i].equals(Lista2[i])) { E gives error on this line: System.out.println (calculatedList (list1, Lista2)); Java.lang.nullPointerException error

  • You have not filled in any information, hence the null error. When the loop goes through the indexes, all are null.

  • I put: String [] list1 = new String [3]; E String [] list1 = new String [5]; Is this what you mean? If so, it gives exactly this error.

  • At what point in the code do you use the scanner to fill the lists? In the code you are not filling either of the two lists, you are just starting them.

  • Right, and how to use the Arrays Scanner?

  • Makes a for iterating at each position of the arrays after instantiated and scaled, and at each position of them you use this Scanner object that you initialize and do this: lista1[i] = sc.nextLine();. And don’t forget to close the Scanner, with ´sc.close().

Show 8 more comments

2 answers

3

First that your algorithm does not define at any time the size of the vectors, before using them, you must define the size of each one:

//neste exemplo iniciei os 2 vetores com o tamanho 4 indices
String [] lista1 = new String [4];
String [] lista2 = new String [4];

Then, you need to use a loop to fill the vectors, respecting the size limit of each one:

System.out.println ("Escreva os Nomes na Primeira Lista: ");

for(int i = 0; i < lista1.length; i++){
    lista1[i] = sc.nextLine();
}

System.out.println ("Escreva os Nomes na Segunda Lista: ");

  for(int i = 0; i < lista2.length; i++){
    lista2[i] = sc.nextLine();
}

According to the logic stated in the question, there is a problem in your method calcularLista, he is not counting or performing the operation correctly.

You need to scroll through the two lists to see which indices list 1 has in common with Lista2, and stop the execution of the second loop when an identical name is found in the two lists:

for (int i = 0; i<lista1.length;i++) {

    for(int z = 0; z<tamanhoLista2;z++){

        if (lista1[i].equals(lista2[z])) {

            cont++;
            break;
        }
    }
}

With this, the method will compare each index of the list1 with each Indice of Lista2 and count only when they are found equal in the two lists.

And to calculate the percentage, you need to divide the result of the found items multiplied by 100, by the size of Lista2, but first you need to transform one of the values to double, in the example, I transformed the size of Lista2 into double:

  public static double calcularLista(String lista1[], String lista2[]) {

        int cont = 0;
        double tamanhoLista2 = lista2.length;

        for (int i = 0; i<lista1.length;i++) {

            for(int z = 0; z<tamanhoLista2;z++){

                if (lista1[i].equals(lista2[z])) {

                    cont++;
                    break;
                }
            }
        }

        return (cont * 100)/tamanhoLista2;
    }

See all your code working on ideone.

  • Running the code on ideone gives error of: "error: reached end of file while Parsing". For what reason?

  • @Beginnerteemjava here is running normally, without any error, strange this. I tested in the 3 browsers I have and none gave this error.

3

Your algorithm has some little problems. The first is the following:

String [] lista1 = new String [];

When you create the array, you must specify its length. Something like this:

String[] lista1 = new String[10];

However, you can say that 10 is too much... or maybe too little... or maybe you should ask the user how many there are. By the way, you’re not asking the user to type anything, you’re just writing on the console without reading anything from there.

So, to read a console number:

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 then, 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 don’t, you can make the list size 1 different from the list size 2.

Missing also read the names. To read a name, you can do this:

String nome = sc.nextLine();

Or already read straight into the array:

nome[i] = sc.nextLine();

And in the case up there, you might want to know where this comes from i. The answer is that you will need to read each of the lists of names using a for and this i shall be the index variable of that for.

When it comes to comparing the lists, you are comparing the element 0 of a list with the element 0 of another list. The 1 of a list with the 1 of the other list. The 2 of a list with the 2 of the other list... But that’s not what you want! For example, imagine this case:

Lista1: Alberto, Fernanda, Marcelo, Rodrigo, Maria, Tatiana
Lista2: Joaquim, Carlos, Maria, Adriana, Fernanda, Marcelo, Alberto

How many names on the list 1 are on the list 2? The correct answer is 4 (Alberto, Fernanda, Marcelo e Maria). But your algorithm won’t find any of those names, because their positions don’t match.

To resolve this, I recommend taking a different approach. You will need to create two bonds for One inside the other. The one from the outside going through the list 1 and the one from within going through the list 2, in order to compare all the elements of a list with all the elements of the other list. When you find an element that matches, you do the cont++; and gives a break;. The break; is important, because once the list 1 element is found, you don’t want to keep looking (and if it continues, you will have problems with lists that have repeated elements).

Finally, one last detail:

return cont/lista2.length;

Here cont is whole and lista2.length is also integer. Thus, an entire division will be performed. Only after the entire division has been performed will the value be converted to an double to be returned. That’s 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 percentage, multiply by 100:

return ((double) (cont * 100)) / lista2.length;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.