Search code examples
javaarraysloopsjoptionpane

How do I print out the first instance of duplicates in an array of randomly generated numbers?


I've printed 10 random numbers in the range 20-50 while storing them in an array. I'm having trouble getting the duplicates found to work. If there's an instance in the array where there's a duplicate found, I'm trying to print out the position where it was found, not the subscript.

For example:

46

24

46

48

44

20

24

46

44

27

First pair of duplicates were found at positions: 1 and 3

Is the output that I'm trying to achieve if there's duplicates and then the same except "No duplicates were generated." if there wasn't any.

import javax.swing.JOptionPane;
public class sheet11t1
{
    public static void main(String[] args)
    {
        String results = "";
        int numbers[] = new int[10];
        int j;
        for(int i = 0; i < numbers.length; i++)
        {
            numbers[i] = (int) ((Math.random() * 31) + 20);
            results += i + "\n";
        }
        boolean duplicateFound = false;
        for(int i = 0; i < numbers.length - 1 && !duplicateFound; i++)
        {
            for(j = i + 1; j < numbers.length && !duplicateFound; j++)
            {
                if(numbers[i] == numbers[j])
                    duplicateFound = true;
            }
        }
        if(duplicateFound)
                results += "First pair of duplicates were found at positions: " + numbers[i + 1] + " and " + numbers[j + 1];
        else
                results += "No duplicates were generated.";
        JOptionPane.showMessageDialog(null, results);
    }
}

Solution

  • What you have to change is the showing of the numbers instead of the index. so for your first loop, change to numbers[i] instead of just i. secondly, In your case of exiting the loop, the i and j are +1, thus when you want to print the index, you just need to specify i and j. below is the codes.

    import javax.swing.JOptionPane;
    public class example {
    
    public static void main(String[] args) {
        String results = "";
        int numbers[] = new int[10];
        int j = 0;
        int i;
        for(i = 0; i < numbers.length; i++)
        {
            numbers[i] = (int) ((Math.random() * 31) + 20);
            results += numbers[i] + "\n";
        }
        boolean duplicateFound = false;
        for(i = 0; i < numbers.length - 1 && !duplicateFound; i++)
        {
            for(j = i + 1; j < numbers.length && !duplicateFound; j++)
            {
                if(numbers[i] == numbers[j])
                    duplicateFound = true;
            }
        }
        if(duplicateFound)
                results += "First pair of duplicates were found at positions: " + (i) + " and " + (j);
        else
                results += "No duplicates were generated.";
        JOptionPane.showMessageDialog(null, results);
    
    }
    
    }