Checking for duplicates

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • oaklander
    New Member
    • Aug 2007
    • 20

    #1

    Checking for duplicates

    I currently have two String variables I check to find if they are duplicates:

    Code:
    String str1 = "red";
    String str2 = "yellow";
    if (str1.equals(str2)){
          System.out.println("Duplicate");
    }
    else{
          System.out.println("Not duplicate");
    }
    Since red is not the same as yellow it would show "Not Duplicate".

    Now how would I check 10 variables to find out if any of them are duplicates?

    Code:
    String str1 = "red";
    String str2 = "yellow";
    String str3 = "green";
    String str4 = "blue";
    String str5 = "red";
    String str6 = "green";
    String str7 = "green";
    String str8 = "white";
    String str9 = "black";
    String str10 = "green";
    In this example red and green have duplicates.

    Please advise how I can do this?
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    I would use a String Array and 2 nested for...loops to iterate through the array, checking for duplicate values.

    If you have them stored as str1, str2, str3,...,strN, then only way you can check for multiples is with many, many if statements (somewhere close to N^2).

    Comment

    • heat84
      New Member
      • Nov 2007
      • 118

      #3
      Every colour can have a boolean representing it e.g isRed which is false before the string red is entered. When the string is entered, the flag is set to true and when someone enters the string any other time the flag will be set to true - if its true , then duplicate should be printed.

      Comment

      Working...