使用while循环java消除数组中的重复项

bbuxkriu  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(420)

基本上,我尝试获取一个多达20个整数的数组,并消除数组中可能存在的重复项。我只能用for循环来实现这一点,但我必须用while循环来实现,因为数组中的数字数量可能多达20个,而且我事先不知道。
这是我的密码:

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]+" ");
         }   
    }
}

它工作,但它只在输入文件有18个整数时工作。

hi3rlvi2

hi3rlvi21#

如果您可能不使用set接口(谁为您做肮脏的工作),您可以使用此代码。

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;
      }

}
lf3rwulv

lf3rwulv2#

我建议你看看 Set 班级。这是消除重复项的最简单、最优雅的方法。

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);
        }
    }
}
bis0qfac

bis0qfac3#

尝试以下操作:

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);

祝你好运!

相关问题