Finding Duplicates in Array and printing them only Once

前端 未结 6 1187

I am trying to loop through my array and find all the numbers that are repeating more than once:

E.G: if there is 1 1 2 3 4

It should print saying \

6条回答
  •  不知归路
    2021-01-21 23:59

    This problem is much simpler and likely faster to solve using a collection. However, as requested here's an answer that uses "just simple array[s]" and no sorting. I've tried not to change your code too much but I refuse to leak resources in the case of an exception.

    import java.io.*;
    import java.util.Arrays;
    import java.util.Scanner;
    
    class Average {
    
         public static void main(String[] args) throws IOException {
    
            int numOfLines = 0;
            int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
            int[] buffer;
            int flag = -1;
    
            File myFile = new File("num.txt");
            try (Scanner Scan = new Scanner(myFile)) {
    
                while(Scan.hasNextLine()) {
                    Scan.nextLine();
                    numOfLines++;
                }
            }
            try (Scanner Scan = new Scanner(myFile)) {
    
                System.out.println("Number Of Lines: " + numOfLines);
    
                buffer = new int[numOfLines];
    
                for(int i=0; i

    Input file "num.txt" (numbers separated by newlines not commas):

    1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3
    

    Output:

    Number Of Lines: 14
    Sum: 91
    Mean: 6
    Dupes: [1, 2, 3, 7]
    

提交回复
热议问题