In Java, write a AllDigitsOdd program that has a method called allDigitsOdd that takes an integer and returns whether every digit of an integer is odd (boolean).
returns true if the integer consists entirely of odd digits (1,3,5,7,9)
returns false if any of its digits are even (0,2,4,6,8)
Consider the use of mod (%).
You should complete the method with integers only. You should not convert the integer to a String
Method call examples:
allDigitsOdd(135319) would return true
allDigitsOdd(-9145293) would return false
Your main method should:

//Prompt the user for an integer.
//You can assume the user always types an integer.
//Then print whether or not the number has all odd digits.

Answer :

mjassim

Answer:

Hi there! The solution for this problem can be implemented a number of ways. Please find my solution below along with the explanation.

Explanation:

The prompts are fairly easily implemented using the Scanner class in Java for user input. In the allDigitsOdd function, we can perform a Math operation on the number being passed into the function to determine the number of digits in the number. We use the log10 function to do this and convert the double value returned to int. This is calculated in the code below as:  "(int)(Math.log10(number) + 1); ". Once we have the number of digits, we write a simple loop to iterate over each digit and perform a modulus function on it to determine if the digit is odd or even. I have declared 2 variables call odd and even that get incremented if the mod function (%) returns a 1 or a 0 respectively. Finally, the result is displayed on the screen.

AllDigitsOdd.java

import java.util.Scanner;

import java.lang.Math;

public class AllDigitsOdd {

 public static void main(String args[]) {

   // print main menu for user selection

   System.out.println("Please enter a number");

   Scanner scan = new Scanner(System.in);

   int selection = scan.nextInt();

   if (allDigitsOdd(selection)) {

     System.out.println("All numbers are odd");

   } else {

     System.out.println("All numbers are not odd");

   }

 }

 public static boolean allDigitsOdd(int number) {

   int digits = (int)(Math.log10(number) + 1);

   int even = 0;

   int odd = 0;

   for (int index = 1; index <= digits; index++) {

       if ((int)(number / Math.pow(10, index - 1)) % 10 % 2 == 0) {

         even += 1;

       } else {

         odd += 1;

       }

   }

   if (even == 0 && odd > 0) {

     return true;

   } else {

     return false;

     //if (odd > 0 && even == 0) {

     //  return true;

     //}

   }

 }

}

Other Questions