Scanner class Methods in Java

Write a Java program to check whether the number is trunk number or not

What is a Trunk Number ?

In programming ,we make programs to check several type of numbers. Today,we are going to learn about Trunk Number. Programmers love to make awkward combinations of numbers and classify them.Lets learn about trunk numbers.

Trunk number is number who becomes greater on reversing.In other words,When we reverse a number and reversed number becomes greater than the original number then that number is called a Trunk Number.

Example:

Assume a number 389 and its reverse number is 983. Compare original and reversed number. What did you find? 983 is greater than 389 , it means the reversed number is greater than the original one.Hence, 389 is Trunk number.

How to check if number is Trunk number or not using Java?

In the post, we are going to write a program to find if number is trunk or not.We will use Scanner class to get input from user.Then using our logic,we will reverse the number and compare both original and reverse numbers.At last, we will print the output on screen.

Lets begin!

Write a Java program to check whether the number is trunk number or not

Write a Java program to check whether the number is trunk number or not


In the above example,
  1. We have four variables, "number " to store the number entered by user ,"temp" to temporary store the the value of "number" variable, "revNum" to store the reverse number, "d" to extract the digits of number and store them.
  2. Till line 10 ,we are getting number from user using Scanner class.Consider the number is 123.
  3. In line 11, we are storing number in "temp" variable. Store 123 in temp.
  4. In line 12, we will run a while loop until the number is greater than 0. Loop will run until 123 is greater than 0.
  5. In line 14, we are extracting digits of number by using Modulus operator. On performing d=number%10, d= 123%10 is equal to 3. This way we can get all digits.Try to solve on a notebook first to understand the logic.
  6. In line 15, by doing revNum= (0 *10)+3; we got 3.We can get 321 as reverse number on each time loop executes.
  7. Inline 16, we are updating the number by dividing it with 10. By doing , number =number /10, we got 12. On each iteration,number will get reduced.And in three iterations, we can get reverse number.
  8. From line 18 to 22, we are checking that the reversed number "revNum" is greater than original number which was stores in "temp" variable.
Note: There are several ways of writing a program.I have explained the simplest method. Try to analyse the output by yourself.

Output: 

Write a Java program to check whether the number is trunk number or not

Practice as much as you can! Happy Coding!


Comments