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);   ...

Java Program to calculate the Strike Rate of a Cricket Batsman

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

WP similar or related posts widget without using any plugin

Hi guys, Recently I was working on some WP website and my client told me that he required a widget for displaying related/similar posts on the single post page. But as his website was already using many plugins, even for some pretty small tasks like this one, I decided not to use another WP plugin (plugins are not good for your WP websites, we will discuss about that on some other post.) I am not explaining the code as it is pretty simple if you are familiar with WP classes. But please let me know if you have any questions related to the PHP code posted below in the comments section or even much better, on Gist. You can add the following code directly in your child theme's functions.php file or you can create a separate file and include this at the bottom of functions.php file. <?php class similar_posts_widget extends WP_Widget {     function __construct()     {         parent::__construct('similar_posts_...