2

I need to write a boolean method called hasEight(), which takes an int as input and returns true if the number contains the digit 8 (e.g., 18, 808).

I don't want to use the "String conversion method".

I've tried the below code, but that only checks for the last digit.

import java.util.Scanner;

public class Verificare {

    public static boolean hasEight(int numarVerificat) {
        int rest = numarVerificat % 10;
        return rest == 8;
    } 

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Introduceti numarul pentru verificare: ");
        int numar = keyboard.nextInt();
        Verificare.hasEight(numar);
        System.out.println("Afirmatia este: " + Verificare.hasEight(numar));
    
        keyboard.close();
    }
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Sebastian Gruia
  • 83
  • 1
  • 1
  • 8

3 Answers3

11

If you don't want to use string conversion methods then i think this method can be used.

public bool hasEight(int number)
{
      while(number > 0)
      {
          if(number % 10 == 8)
              return true;

          number=number/10;
      }
      return false; 
} 
Uday
  • 345
  • 4
  • 8
1

Use the below function.

boolean hasEight(int num) {
    int rem;
    while (num > 0) {
        rem = num % 10;
        if (rem == 8)
            return true;
        num = num / 10;
    }
    return false;
}

In every iteration of the loop, last digit of the number is retrieved (remainder when divided by 10). If it is 8, true is returned. Else, number is divided by 10 (integer division so that last digit is removed) and another iteration is started. When all digits are checked (8 or not), number becomes 0 and loop stops.

1
    public static boolean hasEight(int numarVerificat)
    {
        while(numarVerificat > 0)
          {
              if(numarVerificat % 10 == 8)
                  break;
              numarVerificat=numarVerificat/10;
          }
          return (numarVerificat>0); 
    }