[英]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. 用户输入了一个数字,例如2013或2012,它会检查该数字是否有重复出现的数字,例如2012年为2,但是我不知道从哪里去。
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. 如果第一次出现的
number
与最后一次出现的索引不同,则number
必须出现多次。
public static boolean containsDuplicate(String str, int number) {
return str.indexOf(number) != str.lastIndexOf(number);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.