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;
//}
}
}
}