Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - (Print distinct numbers)

I'm trying to solve this problem:

"Write a program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by exactly one space."

My code at the moment does not save all distinct numbers and at time repeatedly display 0. If anyone can see where my logic has gone wrong, any tip will be helpful. Thank you!

public class PracticeProject
{
public static void main(String args[])
{
    int[] number = new int[10];
    int[] counter = new int[10];
    int numcounter = 0;

    numGen(number);
    numcounter = distNum(number, counter, numcounter);
    dispDist(counter, numcounter);
}

public static void numGen(int[] number)
{
    Random rand = new Random();

    for (int i = 0; i < number.length; i++)
    {
        number[i] = rand.nextInt(10);
        System.out.print(number[i] + " ");
    }

    System.out.println();
}

public static int distNum(int[] number, int[] counter, int numcounter)
{
    for (int i = 0; i < number.length; i++)
    {           
        for (int j = 0; j <= i; j++)
        {
            if (counter[j] == number[i])
            {
                break;
            }

            if (j == i)
            {
                counter[j] = number[i];
                numcounter++;
            }
        }
    }
    return numcounter;
}

public static void dispDist(int[] counter, int numcounter)
{
    for (int i = 0; i < numcounter; i++)
    {
        System.out.print(counter[i] + " ");
    }
}

}

like image 633
KevinG Avatar asked Dec 30 '25 23:12

KevinG


1 Answers

The problem is with the logic in your distNum() method, which was not correctly removing all duplicates from the output array. Try using this version instead:

public static int distNum(int[] number, int[] counter, int numcounter) {
    for (int i = 0; i < number.length; i++) {
        boolean isUnique = true;
        for (int j = 0; j < numcounter; j++) {
            if (counter[j] == number[i]) {
                isUnique = false;
                break;
            }
        }
        if (isUnique) {
            counter[numcounter] = number[i];
            numcounter++;
        }
    }
    return numcounter;
}

I walk through the array of random numbers, and for each one I scan counter to see if the value has already been encountered. If it be a duplicate, then it does not get added to the unique list.

This method was tested along with the rest of your original code using IntelliJ, and it appears to be working correctly.

like image 143
Tim Biegeleisen Avatar answered Jan 02 '26 13:01

Tim Biegeleisen