How to print distinct array elements in java?

here’s the code for printing distinct elements from a list of elements in an array(I got this from a website).

  package pattern;

  import java.util.*;

  class Pattern{
  public static void main(String[] args){

  int[] num=new int[6];

  //method to enter elements inside 'num' array
  System.out.println("Enter the numbers: ");
  getEle(num);

  //method to print distinct elements from array
  System.out.println("Printing distinct elements:");
  printDis(num);

  }

    public static void getEle(int[] num){

    Scanner in=new Scanner(System.in);
    for(int i=0;i<num.length;i++)
    {
        num[i]=in.nextInt();
    }

    }


   public static void printDis(int[] num){

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

       int j;
    for ( j=0; j<=i; j++)
    {
       if (num[i] == num[j])
           break;
    }

    if (i == j)
      System.out.print(num[i]+" ");
    }
    }



    }

basically i’m not getting ‘printDis’ function i.e.

   public static void printDis(int[] num){

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

       int j;
    for ( j=0; j<=i; j++)
    {
       if (num[i] == num[j])
           break;
    }

    if (i == j)
      System.out.print(num[i]+" ");
    }
    }

can someone explain me the loop and what this

           if (num[i] == num[j])
           break;

and.,

      if (i == j)
      System.out.print(num[i]+" ");

this code does.

Source: java

Leave a Reply