1

In this program I am supposed to figure out if the integer that the user enters contains a certain digit (in this case 7 and 3), and then return a boolean. So far I have:

public static boolean contains(int num, int x) {
    Scanner input = new Scanner(System.in);
    int currentLength = numberDigits(num); //method that counts the number of digits in the inputed integer

    int digit;   // current first digit

    int firstNumber = firstNum(num);
    boolean digitTrue = false;   

    while (currentLength > 0 ) {
        digit = firstNumber;
        if (num == x)
        {
            digitTrue= true;
        } else {
            digitTrue= false;
        }
    }
    return digitTrue;
}
UnknownJ25
  • 21
  • 5
  • Possible duplicate of [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – UnknownJ25 Apr 05 '18 at 00:04

3 Answers3

1

The best way to solve this that I know of is to use %. % or Modulus returns the remainder of one number / by another number. For example 5 % 2 = 1 or 355 % 10 = 5. If you are looking only to check a large number for single digit numbers I would suggest this method

public static boolean contains(int num, int x){

while(num >= 0){
    if (num % 10 == x){
        return true;
    }
    if (num > 0){
        num = num / 10;
    }else{
        return false;
    }
}
return false;
}

Hope this Helps

JT attack
  • 87
  • 1
  • 1
  • 8
1

By invoking module 10 on a number you retrieve the last digit of this number.
Perform it on num, then perform it on num/10, then on num/100 until you iterates on all digits (that is while the division result > 0).

You could so write :

int currentNumber = num;
while (currentNumber > 0 ) {
    if (currentNumber % 10 == x){
        return true;
    }
    currentNumber = currentNumber / 10;
}
return false;

Note that the boolean variable is helpless.
You want to return true as soon as a digit equals to x, so return true directly in the conditional statement block and return false; after the while statement.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Fails for `contains (0, 0)`, which seems to be a legitimate question for me. – user unknown Apr 04 '18 at 23:08
  • Indeed it is a corner case potentially to handle. A `do/while` as you suggested or conditional statement before the loop could do the job : `if (num== 0 && x==0){return true;}` – davidxxx Apr 04 '18 at 23:25
1

This code works correctly for contains (0, 0) too:

boolean contains (int num, int x) {
    do {
        if (num % 10 == x){
            return true;
        }
        num /= 10;
   } while (num > 0);
   return false;
}

For x > 9 or x < 0, you have to write an guard statement and for num (and/or x) < 0 you should take the Math.abs first.

user unknown
  • 35,537
  • 11
  • 75
  • 121