Java Program to Reverse a Number. Use Swing showInputDialog to get Input

The following program will accept a number through input dialog box and reverse it.

Procedure for Reversing a Number.

1. lastDigit=Modulus the given by 10

2. reverse = reverse * 10+lastDigit

3. Divide the number by 10

4. Continue the above steps until the given number becomes zero.

 

Consider the number 25 .

Reverse=0;  // to store reversed number

Step 1 : 25 Mod 10 = 5

Step 2 : 25 / 10 = 2

Step 3 : Reverse=0*10+5 = 5

 

Now the number 25 becomes 2

Again Follow the above steps until the number becomes zero

Step 1 : 2 Mod 10 = 2

Step 2 : 2 / 10 = 0

Step 3 : Reverse=5*10+2 = 52

Now the value of Reverse is 52

 

// Code Begins

package com.javaonline;
import javax.swing.JOptionPane;

public class ReverseANumber {

	public static void main(String [] args){

	try{

			String input = JOptionPane.showInputDialog("Enter any number: "); // Displays Input Dialog Box to enter number

			int num= Integer.parseInt(input); // converts string to number

			int orgNum=num;

			int rev=0;

			while(num>0)

			{

				int d=num%10;

				num=num/10;

				rev=rev*10+d;

			}

			System.out.println("Reverse("+orgNum+ ") = "+ rev);

		}

			catch(Exception e){

					System.out.println("Please enter Integer!");

			}	

		}

	} 

Run the program

Give number as 12345 in the input dialog box

Output : Reverse a number