OOP-JAVA Practical 15

OOP-JAVA Practical 15
  • Aim: Write the bin2Dec (string binary String) method to convert a binary string into a decimal number. Implement the bin2Dec method to throw NumberFormatException if the string is not a binary string.
  • Code:
    import java.util.Scanner;
    public class practical15 {
        public static int bin2Dec(String binary) throws NumberFormatException{
            int decimal;
            for(int i=0;i<binary.length();i++){
                if (binary.charAt(i)>'1') {
                    throw new NumberFormatException("Enter valid Binary number");
                }
            }
            decimal=Integer.parseInt(binary, 2);
            return decimal;
        }
        public static void main(String[] args) {
            Scanner s= new Scanner(System.in);
            System.out.println("Enter Binary number:");
            String str=s.nextLine();
            try {
                System.out.println("Decimal value : "+bin2Dec(str));
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
  • Output:
    Output of practical 15

Comments