Java array shows specific items

Asked

Viewed 51 times

1

Hello, guys I’m having a doubt for example I have Array A {1,2,3,4,5} I do another array B {1,2,3} with the items I wish to exclude from array A, and show the items that were left ex 4 and 5 , but I’m with stopping an if inside a for and the answer comes out completely loca , someone could help me ?

I can’t use arraylist.

ex: A = {1,2,3,4,5}

new array with items I wish not to be displayed :

B = {1,2,3}

inside the go with stop and show only different items

4 and 5

Below is the code I tried

int qtdpessoas ;
        int exclui ;
        Scanner sc = new Scanner(System.in);
        qtdpessoas = sc.nextInt();
        int idpessoa [] = new int [qtdpessoas];


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

            idpessoa[i]= sc.nextInt();
            }

        exclui = sc.nextInt();
        int paraexcluir [] = new int [exclui];

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

        for (int i = 0; i < idpessoa.length; i++) {
            for (int j = 0; j < paraexcluir.length; j++) {
                if (idpessoa[i]!= paraexcluir[j]) {
                System.out.println(idpessoa[i]);
                }
            }
  • Have you tried anything? If you have, you can post the code?

  • Yes, I’ll re-edit here and if you can take a look

1 answer

1


To get the result you want to make the following changes to your code:

  • In the if check that the elements are equal, and if they are, skip to the next loop iteration;
  • Add a else if check if you are in the last element and if you are using the System.out.println, so you will have tested all the elements and this condition will only be satisfied if no element is equal.

Your if will be more or less like this:

if (idpessoa[i] == paraexcluir[j]) {
  break;
} else if (j == (paraexcluir.length - 1)) {
  System.out.println(idpessoa[i]);
}

Browser other questions tagged

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