In the following code, I am trying to check if an int (converted to String) contains duplicate digits.
public static boolean hasDupes(int n)
{
String number = new String();
number = Integer.toString(n);
int digit = 0;
System.out.println(num.indexOf(digit));
System.out.println(num.lastIndexOf(digit));
while(digit < 10)
{
if(number.indexOf(digit) != number.lastIndexOf(digit))
{
return true;
}
digit++;
}
//System.out.println(n);
return false;
}
I put in the System.out.println lines because I was unsure as to why my method wasn’t working. They always print out ‘-1’. I dont understand how an index can be -1, and why it isn’t working.
digitis anint. Passed toindexOfit will be used as a character number, so you’ll be looking for char 0 (the null character) instead of the ASCII digit'0'. Naturally that character isn’t in the string, so you get -1.You’re probably thinking of the
indexOf(String)method. egOr, if you want to do it with a range of character codes: