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
cse gtu, gtu study material for computer engineering students gujarat technological university oop lab manual solution

gtu oop lab manual,

oop GTU Practical,

oop Programs,

Object oriented Programming,

Gtu study material 3140705,

OOP 3140705,

oop practical list,

Java Programming,

gtu oop practical,

oop lab solution gtu

Comments

YouTube

Popular posts from this blog

GTU OOP Programs - 11

Mini project ideas for Operating System

GTU OS Program - 8