Skip to main content

Java program to perform binary addition


import java.util.*;
public class BinaryAddition {
    private Scanner scan;
    private String num1, num2, binary;
    public BinaryAddition() {
        scan = new Scanner(System.in);
        num1 = num2 = binary = "";
    }
    public void input() {
        try {
            System.out.printf("Enter First Number: ");
            num1 = scan.next();
            if (!isBinary(num1)) {
                System.err.printf("Binary Number Expected.");
                System.exit(0);
            }
            System.out.printf("Enter Second Number: ");
            num2 = scan.next();
            if (!isBinary(num2)) {
                System.err.printf("Binary Number Expected.");
                System.exit(0);
            }
        } catch (InputMismatchException | NumberFormatException e) {
            System.err.println("Error Occurred!\n" + e.getMessage());
        }
    }
    private boolean isBinary(String num) {
        try {
            char ch;
            for (int i = 0; i < num.length(); i++) {
                ch = num.charAt(i);
                if (Integer.parseInt(Character.toString(ch)) != 0 && Integer.parseInt(Character.toString(ch)) != 1) {
                    return false;
                }
            }
        } catch (IndexOutOfBoundsException | NullPointerException e) {
            System.err.println("Error Occurred!\n" + e.getMessage());
            System.exit(0);
        }
        return true;
    }
    public void compute() {
        try {
            long len1, len2;
            len1 = num1.length();
            len2 = num2.length();
            if (len1 != len2) {
                if (len1 > len2) {
                    int dif = (int) ((int) len1 - len2);
                    String d = "";
                    for (int i = 0; i < dif; i++) {
                        d += "0";
                    }
                    num2 = d + num2;
                } else {
                    int dif = (int) ((int) len2 - len1);
                    String d = "";
                    for (int i = 0; i < dif; i++) {
                        d += "0";
                    }
                    num1 = d + num1;
                }
            }
            System.out.println("Binary Addition Rules:-\n1. 0 + 1 = 1\n2. 1 + 0 = 1\n3. 1 + 1 = 10\n4. 1 + 1 + 1 = 11");
            addition(num1, num2);
        } catch (NullPointerException | IndexOutOfBoundsException | NumberFormatException e) {
            System.err.println("Error Occurred!\n" + e.getMessage());
            System.exit(0);
        }
    }
    public void addition(String num1, String num2) {
        String binary = "", carry = "0";
        num1 = "0" + num1;
        num2 = "0" + num2;
        for (int i = num1.length() - 1; i >= 0; i--) {
            int sum;
            sum = Integer.parseInt(carry) + Integer.parseInt(Character.toString(num1.charAt(i))) + Integer.parseInt(Character.toString(num2.charAt(i)));
            if (sum == 2) {
                binary += "0";
                carry = "1";
            } else if (sum == 3) {
                binary += "1";
                carry = "1";
            } else {
                binary += Integer.toString(sum);
                carry = "0";
            }
        }
        this.binary = new String(new StringBuffer(binary).reverse());
        while (this.binary.startsWith("0")) {
            this.binary = this.binary.substring(1);
        }
        System.out.println("Result: " + this.binary);
    }
    public static void main(String[] args) {
        BinaryAddition ba = new BinaryAddition();
        ba.input();
        ba.compute();
    }
}

Output:-
Enter First Number: 1111
Enter Second Number: 1111
Binary Addition Rules:-
1. 0 + 1 = 1
2. 1 + 0 = 1
3. 1 + 1 = 10
4. 1 + 1 + 1 = 11
Result: 11110

Comments

Popular posts from this blog

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Vanilla Javascript each()

JQuery's each() is very useful when iterating through elements. But you don't want to use JQuery in your project you can simply add the following javascript code which works somewhat similar to the JQuery's each function. Here the fnc parameter is the function string which is converted to a valid function call replacing all the $(this) with this /**  * This function binds a particular function to every element with the specified selector. It is somewhat same as JQuery's each() with less functionality  * @param {String|DOMElement} selector  * @param {Function} fnc  */ function each(selector, fnc) {     var elem;     if (typeof selector === "string") {         elem = $_(selector);     } else {         elem = selector;     }     fnc = (fnc.toString().replace("$(this)", "elem") + "();").replace("function () {", "").replac...

Java Program to display Welcome Message

import java.io.*;// I/O package imported. public class Welcome{        //class name is "Welcome"     public Welcome(){      //constructor declaired to print the message.         System.out.println("Welcome to Java Programming Language!");/* System.out.println is used for output. Welcome Message is written within " ".*/     }//display() closes here.     public static void main(String[] args){        //main() is declaired to declair an object in it.         Welcome obj=new Welcome();  //Object "Obj" is bean created.     }//main() closes. }//class "Welcome" ends here. Above program displays the message which is written by you in " ".  In programs "/*" and "*/" are use for multiple line comment(s) and "//" is use for single line comment. Code line "Welc...