开发者

Java indexOf and lastIndexOf return -1?? Please Help

开发者 https://www.devze.com 2023-01-23 01:51 出处:网络
In the following code, I am trying to check if an int (converted to String) contains duplicate digits.

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++;
    }
    //Syste开发者_开发技巧m.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.


number.indexOf(digit)

digit is an int. Passed to indexOf it 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. eg

var dstr= ""+digit;
if (number.indexOf(dstr) != number.lastIndexOf(dstr))
    return true;

Or, if you want to do it with a range of character codes:

for (char digit= '0'; digit<='9'; digit++)
    if (number.indexOf(digit) != number.lastIndexOf(digit))
        return true;


This is probably happening because you're calling indexOf with an int parameter, but it's looking for a character with that unicode value, NOT the string value. Convert the digit to a String, like so:

while(digit < 10)
    {
      String digitString = String.valueOf(digit);
      if(number.indexOf(digitString) != number.lastIndexOf(digitString))
      {
      ...
0

精彩评论

暂无评论...
验证码 换一张
取 消