Tuesday, September 22, 2009

Java Code to Convert Binary to Decimal

Java has deal with many different situations. So Java Code Online is going to discuss a case when a number entered as binary is to be converted to a decimal number. A binary number which consists of only 1 and 0, while a decimal number is a number which consists of numbers between 0-9.

We normally use decimal numbers in our daily purposes. Binary numbers on the other hand are very important and used for computers data transfer.

The Java code for converting a binary number to a decimal number, starts by asking the user to enter a binary number. The result is a decimal number which is displayed to the user. In case the number entered is not a binary number, i.e. it contains numbers other then 0 and 1. In that a NumberFormatException will be thrown. I have catch this exception, so that the developer can use there custom message in that place.

The Java Code is displayed below:-

/////////////////////////////////////

package developer;

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
      
        System.out.println("Enter a binary number: ");
        Scanner scanStr = new Scanner(System.in);
              
        int decimalNum = 0;      
              
        if(scanStr.hasNext())
        {   
            try
            {
                decimalNum = Integer.parseInt(scanStr.next(),2);
                System.out.println("Binary number in decimal is: "+decimalNum);  
            }
            catch(NumberFormatException nfe)
            {
                System.out.println("The number is not a binary number.");
            }
        }  
    }
}


/////////////////////////////////////

When this code is executed on my system, the output is as shown below.
/////////////////////////////////////

Enter a binary number:
10100011
The binary number in decimal is: 163

/////////////////////////////////////

In case the number entered is not a binary number, then the output is as shown below:-

/////////////////////////////////////

Enter a binary number:
123456
The number is not a binary number.

/////////////////////////////////////

Hope that I was able to make my point clear. If you liked the article then do post a comment. Kepp checking Java Code Online for more Java Codes.

Related Java Codes
Java Code to Convert Decimal to Binary

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.