TheEmoLoser
TheEmoLoser

Reputation: 11

Eliminate duplicates from array using while loop java

Basically I'm trying to take an array of up to twenty integers and eliminate duplicates that are potentially in the array. I have only been able to do this with a for loop, but I must do it with a while loop since the amount of numbers in the array can be up to twenty and I won't know beforehand.

Here's my code:

import java.util.Scanner;
import java.io.*;

public class Main
{
    public static void main(String[] args) throws FileNotFoundException {
        
        //Gets data from file and assigns variables
        Scanner input = new Scanner(new File("in.file"));
        int num = 18;
        int[] numberList = new int[num];
        
        //Displays that which is in the file 
        System.out.printf("The original integers are: ");
        for (int z = 0; z < numberList.length; z++) {
            numberList[z] = input.nextInt();
            System.out.printf(numberList[z]+" ");
        }
        
        //Activates EliminateDuplicates
        EliminateDuplicates(numberList, num);
    }
    
    //Method to sift through data and get rid of duplicates 
    public static int EliminateDuplicates(int[] numberList, int num) {
        
        //Parameter array
        int[] newInt = new int[num];
        int[] array = new int[numberList.length];
        int arrayList = 0;
            for (int c = 0; c < numberList.length; c++) {

        //If parameter and integer are the same the boolean is true 
        boolean duplicate = false;
            for (int b = 0; b < numberList.length; b++) {
                if (array[b] == numberList[c]) {
                    duplicate = true;
                }
            }
            //Incase duplicate becomes true
            if (!duplicate) {
                array[arrayList++] = numberList[c];
            }
        }
        
        //Final array for output
        newInt = new int[arrayList];
            for (int c = 0; c < arrayList; c++) {
            newInt[c] = array[c];
        }

        //Returns num and activate PrintIntegers
        PrintIntegers(newInt);
        return num;
    }
    
    //Method for the output
    public static void PrintIntegers(int[] newInt) {
    
    //Prints the output
    System.out.printf("\nThe distinct integers are: ");  
        for (int x = 0; x < newInt.length; x++) {
            System.out.printf(newInt[x]+" ");
         }   
    }
}

It works, but it only works when the input file has 18 integers.

Upvotes: 1

Views: 478

Answers (3)

sgtcortez
sgtcortez

Reputation: 427

if you might not use the Set interface(who does the dirty work for you) you can use this code.

public class Main { 

    public static void main(String[] args) throws FileNotFoundException {
        
        //Gets data from file and assigns variables
        Scanner input = new Scanner(new File("in.file"));
        int num = 18;
        int[] numberList = new int[num];
        
        //Displays that which is in the file 
        System.out.printf("The original integers are: ");
           
           final int index = 0; // Just be know where we must put the last element.
           for (int z = 0; z < numberList.length; z++) {
             final int number = input.nextInt();
             final boolean inserted = insert(numberList, index, number);
             if(inserted) index++;
        }
        // might print null, if there were duplicate elements in the user input.
        Arrays.toString(numberList);
    }



   /**
      * This is a type of Insertion Sort, with some modifications made by myself.
      */
      static boolean insert(Integer[] array, int length, int value) {
          int initial = length; // The index that we will insert the new element
          for(int index = length - 1; index >= 0; index-- ) { 
              if(array[index] > value) { // If the element is bigger than our input
                  initial--; 
              } else if ( array[index] == value ) { // the element is already in the array
                  return false;
              } else {
                  break;
              }
          }
          // Moves the element that are bigger than our input value.
          // this is array[CURRENT_INDEX + 1] = array[CURRENT_INDEX]
          // We start with the last element, so we will not lose any element with the move 
          for(int index = length; index > initial; index--) {
              array[index] = array[index - 1];
          }
          // Just put the value
          array[initial] = value;      
          return true;
      }


}

Upvotes: 0

Jamie Bisotti
Jamie Bisotti

Reputation: 2685

Try something like this:

    final Set<Integer> uniqueIntegers = new HashSet<>();
    try (final Stream<String> lines = Files.lines(Path.of("in.file"))) {
        lines.map(Integer::parseInt)
                .forEach(uniqueIntegers::add);
    }
    System.out.println(uniqueIntegers);

Good luck!

Upvotes: 1

Ismail Durmaz
Ismail Durmaz

Reputation: 2621

I recommend you looking at Set classes. That is the easiest and elegant way of eliminating duplicate items.

import java.util.*;
import java.io.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {

        //Gets data from file and assigns variables
        Scanner input = new Scanner(new File("in.file"));

        List<Integer> numberList = new ArrayList<>();
        while (input.hasNext()) {
            numberList.add(input.nextInt());
        }

        Set<Integer> uniqueNumbers = new HashSet<>(numberList);
        for (Integer uniqueNumber : uniqueNumbers) {
            System.out.println(uniqueNumber);
        }
    }
}

Upvotes: 0

Related Questions