GTU OOP Program - 15
15). Write the bin2Dec (string binary String) method to convert a binary string into a decimal number. Implement the bin2Dec method to throw a NumberFormatException if the string is not a binary string.
- import java.util.Scanner;
- class Program_15 {
- public static int bin2Dec(String binString) throws NumberFormatException {
- int decimal = 0;
- int strLength = binString.length();
- for (int i = 0; i < strLength; i++) {
- if (binString.charAt(i) < '0' || binString.charAt(i) > '1') {
- throw new NumberFormatException("Please Enter a Binary String");
- }
- decimal += (binString.charAt(i) - '0') * Math.pow(2, strLength - i - 1);
- }
- return decimal;
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter Binary String : ");
- String str = input.nextLine();
- try {
- System.out.println("Value of binary to decimal is : " + bin2Dec(str));
- } catch (NumberFormatException e) {
- System.out.println(e);
- }
- }
- }
Output
Comments