Java Code Example: prints out indices of all pairs of numbers

The code is an example of a Java program to find and display duplicate elements in an array. Here’s an explanation of the code:

  1. The getPairs method takes an array of integers as input and finds duplicates within the array.
  2. The method uses two for loops to traverse the array. The outer loop i starts from the first element of the array and the inner loop j starts from the next element.
  3. The method checks if the elements at indices i and j are equal. If they are equal, the method prints a message indicating the number is included twice, along with the indices where it occurs.
  4. The main method declares an array of integers called myList and calls the getPairs method, passing myList as an argument.
  5. The output of the program will be a list of duplicates in the array, including the value of the duplicate and the indices where it occurs.
import java.util.Scanner;

class ArrayExample {
    public static void getPairs(int[] myList) {
        for (int i = 0; i < myList.length; i++) {
            for (int j = i + 1; j < myList.length; j++) {
                if (myList[i] == myList[j]) {
                    System.out.println("Number " + myList[i] + " is included two times, at indices " + i + " and " + j);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] myList = { 3, 5, 6, 7, 8, 4, 2, 5, 4, 2 };

        getPairs(myList);
    }
}
Output
Number 5 is included two times, at indices 1 and 7
Number 4 is included two times, at indices 5 and 8
Number 2 is included two times, at indices 6 and 9