Skip to main content

Java program to perform number system conversions


import java.util.*;
interface ConversionBase {
    Scanner scan = new Scanner(System.in);
    byte bin = 2, dec = 10, hex = 16, oct = 8;
    char hex1[] = new char[]{'A', 'B', 'C', 'D', 'E', 'F'};
    int hex2[] = new int[]{10, 11, 12, 13, 14, 15};
}
class Number implements ConversionBase {
    String nm;
    char ch;
    long num;
    byte base;
    int i;
    public Number() {
        nm = "\0";
        ch = '\0';
        num = i = base = 0;
    }
    public boolean isBinary(long num) {
        nm = Long.toString(num);
        for (; i < nm.length(); i++) {
            ch = nm.charAt(i);
            if (Integer.parseInt(Character.toString(ch)) > bin - 1) {
                return false;
            }
        }
        return true;
    }
    public boolean isDecimal(long num) {
        nm = Long.toString(num);
        for (; i < nm.length(); i++) {
            ch = nm.charAt(i);
            if (Integer.parseInt(Character.toString(ch)) > dec - 1) {
                return false;
            }
        }
        return true;
    }
    public boolean isOctal(long num) {
        nm = Long.toString(num);
        for (; i < nm.length(); i++) {
            ch = nm.charAt(i);
            if (Integer.parseInt(Character.toString(ch)) > oct - 1) {
                return false;
            }
        }
        return true;
    }
    public boolean isHexadecimal(String num) {
        nm = num;
        for (; i < nm.length(); i++) {
            ch = nm.charAt(i);
            if (Character.isDigit(ch) == false) {
                return hexadecimal(ch);
            }
        }
        return true;
    }
    private boolean hexadecimal(char ch) {
        for (i = 0; i < hex1.length; i++) {
            if (hex1[i] == ch) {
                return true;
            }
        }
        return false;
    }
    public char toHexadecimalCharacter(long num) {
        for (i = 0; i < hex2.length; i++) {
            if (num == hex2[i]) {
                return hex1[i];
            }
        }
        return Long.toString(num).charAt(0);
    }
    public char toHexadecimalCharacter(int num) {
        return toHexadecimalCharacter(Long.parseLong(Integer.toString(num)));
    }
    public int toHexadecimalNumber(char ch) {
        for (i = 0; i < hex1.length; i++) {
            if (hex1[i] == ch) {
                return hex2[i];
            }
        }
        return Integer.parseInt(Character.toString(ch));
    }
    public byte setBase(int choice) {
        if (choice == 1) {
            base = 2;
        } else if (choice == 3) {
            base = 8;
        } else if (choice == 5) {
            base = 16;
        } else if (choice == 2) {
            base = 2;
        } else if (choice == 4) {
            base = 8;
        } else if (choice == 6) {
            base = 16;
        }
        return base;
    }
    public boolean isValidNumber(long num, int choice) {
        if (choice == 1 || choice == 3 || choice == 5) {
            return isDecimal(num);
        } else if (choice == 2) {
            return isDecimal(num);
        } else if (choice == 3) {
            return isOctal(num);
        }
        return false;
    }
    public boolean isValidHexadecimalNumber(String num) {
        return isHexadecimal(num);
    }
    public long getNumber(int choice) {
        if (choice == 1 || choice == 3 || choice == 5) {
            System.out.printf("Enter Decimal Number: ");
        } else if (choice == 2) {
            System.out.printf("Enter Binary Number: ");
        } else if (choice == 4) {
            System.out.printf("Enter Octal Number: ");
        }
        if (!(choice == 6)) {
            num = scan.nextLong();
        }
        return num;
    }
    public String getHexadecimalNumber() {
        System.out.printf("Enter Hexadecimal Number: ");
        return scan.next().toUpperCase();
    }
}
class Conversion extends Number {
    int choice, j;
    byte base;
    long num, res;
    String nm, pow;
    char ch;
    StringBuffer result;
    public Conversion() {
        num = res = choice = j = base = 0;
        nm = pow = "\0";
        ch = '\0';
    }
    public void input() {
        try {
            do {
                System.out.println("MENU\n1. Decimal To Binary\n2. Binary To Decimal\n3. Decimal To Octal\n4. Octal to Decimal\n5. Decimal To Hexadecimal\n6. Hexadecimal To Decimal");
                System.out.printf("Your Choice: ");
                choice = scan.nextInt();
            } while (choice > 6);
            base = setBase(choice);
        } catch (NumberFormatException | InputMismatchException | NullPointerException e) {
            System.err.println("Error Occurred!\n" + e.getMessage());
            System.exit(0);
        }
    }
    public void compute() {
        if (!(choice == 6)) {
            num = getNumber(choice);
            isValidNumber(num, choice);
        } else {
            nm = getHexadecimalNumber();
            isValidHexadecimalNumber(nm);
        }
        if (choice == 1 || choice == 3 || choice == 5) {
            decimalToOther(num, base);
        } else if (choice != 6 && choice == 2 || choice == 4) {
            otherToDecimal(num, base);
        }
        if (choice == 6) {
            hexadecimalToDecimal(nm);
        }
    }
    public void decimalToOther(long num, byte base) {
        while (num != 0) {
            int rem = (int) num % base;
            res = rem;
            if (res > 9) {
                pow += toHexadecimalCharacter(res);
            } else {
                pow += Long.toString(res);
            }
            num /= base;
        }
        result = (new StringBuffer(pow)).reverse();
        display(result.toString());
    }
    public void otherToDecimal(long num, byte base) {
        nm = Long.toString(num);
        for (i = nm.length() - 1; i >= 0; i--) {
            ch = nm.charAt(i);
            res += Integer.parseInt(Character.toString(ch)) * (int) Math.pow(base, j);
            j++;
        }
        pow = Long.toString(res);
        display(pow);
    }
    public void hexadecimalToDecimal(String nms) {
        j = 0;
        for (i = nms.length() - 1; i >= 0; i--) {
            ch = nms.charAt(i);
            res += toHexadecimalNumber(ch) * (int) Math.pow(base, j);
            j++;
        }
        pow = Long.toString(res);
        result = (new StringBuffer(pow)).reverse();
        display(result.toString());
    }
    public void display(String result) {
        System.out.println("Converted: " + result);
    }
}
public class NumberSystem {
    public static void main(String[] args) {
        Conversion Con = new Conversion();
        Con.input();
        Con.compute();
    }
}

Output:-
MENU
1. Decimal To Binary
2. Binary To Decimal
3. Decimal To Octal
4. Octal to Decimal
5. Decimal To Hexadecimal
6. Hexadecimal To Decimal
Your Choice: 5
Enter Decimal Number: 1875
Converted: 753

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