Write a Java program for this question.
Write a program to input a number
and print whether it is a two digit
number or not.
Answers
Answer:
Explanation:
Scanner in = new Scanner(System.in);
System.out.print("Enter a 2 digit number: ");
int orgNum = in.nextInt();
int num = orgNum;
int digit1 = num % 10;
num /= 10;
/*
* If num becomes 0 after extracting first digit
* it means that user entered a single digit number.
* We should check for such invalid inputs.
*/
if (num == 0) {
System.out.println("Invalid input. Entered number is not a 2 digit number");
System.exit(0);
}
int digit2 = num % 10;
num /= 10;
/*
* If num does not become 0 after extracting second digit
* it means that entered number has 3 or more digits.
* We should check for such invalid inputs.
*/
if (num != 0) {
System.out.println("Invalid input. Entered number is not a 2 digit number");
System.exit(0);
}
int digitSum = digit1 + digit2;
int digitProduct = digit1 * digit2;
if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");
}
}
We first accept the number from the user with the help of scanner class and store it in orgNum int variable. As we will truncate the number, it is good to make a copy of it to preserve the original input. We will need the original number later in the program.
int digit1 = num % 10;
num /= 10;
/*
* If num becomes 0 after extracting first digit
* it means that user entered a single digit number.
* We should check for such invalid inputs.
*/
if (num == 0) {
System.out.println("Invalid input. Entered number is not a 2 digit number");
System.exit(0);
}
int digit2 = num % 10;
num /= 10;
/*
* If num does not become 0 after extracting second digit
* it means that entered number has 3 or more digits.
* We should check for such invalid inputs.
*/
if (num != 0) {
System.out.println("Invalid input. Entered number is not a 2 digit number");
System.exit(0);
}