简体   繁体   中英

How to check if a number contains more than 1 of the same digit? (Java)

I'm trying to do this:

User inputs a number for example 2013 or 2012 and it checks if the number has any reoccurring digits like in 2012 there is 2 but I don't know where to go from here.

   public static boolean hasDuplicates(String text){
        for(int i = 0; i < text.length() - 1; i++){
            for(int j = i + 1; j < text.length(); j ++){
                if(text.charAt(i) == text.charAt(j)){
                    return true;
                }
            }
        }
        return false;
    }

You can make it this way:

public static boolean containsDuplicate(int number) {
    String strNum = number.toString();
    for(int i=0; i < strNum.length() -1 ; i++){
          if( containsDuplicatedValue(strNum, strNum.charAt(i) )
              return true;
    }
    return false;
}

private static boolean containsDuplicatedValue(String str, char searchFor) {
    return str.indexOf(searchFor) != str.lastIndexOf(searchFor);
}

Here is a way to check for duplicates. If the first occurrence of number has a different index than the last occurrence, then number must occur more than once.

public static boolean containsDuplicate(String str, int number) {
    return str.indexOf(number) != str.lastIndexOf(number);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM