Skip to content
Advertisement

N times problem while iterating through loop in Duplicate element program

import java.util.*;
public class TestClass {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    String[] val = new String[n];
    scan.nextLine();
    for (int i = 0; i < n; i++) {
      val[i] = scan.nextLine();
    }
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        if (val[i].equals(val[j])) {
          System.out.println(val[i]);
        }
      }
    }
  }
}

This is a simple code for finding duplicate array value but I need an else part where it should print “No duplicate found” but the problem is as I am iterating it through a loop it’s printing N times the output.

INPUT

cat 
dog 
frog
owl

OUTPUT

No duplicate found

Advertisement

Answer

you can have a check variable for example

        boolean duplicatefound = false;
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                if (val[i].equals(val[j]))
                {
                    System.out.println(val[i]);
                    duplicatefound = true;
                }
            }
        }

        if(duplicatefound)
        {
            System.out.println("duplicate found");
        }else
        {
            System.out.println("No Duplicated found");
        }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement