Java Code to Convert Binary to Decimal
Java has deal
with many different situations. We 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.
/////////////////////////////////////