This program converts numbers between binary, octal, decimal, and hexadecimal representations. It contains functions to convert decimal to and from binary, octal, and hexadecimal. The main method gets a number and type from the user, checks if the number is valid, and calls the appropriate conversion functions to output the results in all number bases.
This program converts numbers between binary, octal, decimal, and hexadecimal representations. It contains functions to convert decimal to and from binary, octal, and hexadecimal. The main method gets a number and type from the user, checks if the number is valid, and calls the appropriate conversion functions to output the results in all number bases.
This program converts numbers between binary, octal, decimal, and hexadecimal representations. It contains functions to convert decimal to and from binary, octal, and hexadecimal. The main method gets a number and type from the user, checks if the number is valid, and calls the appropriate conversion functions to output the results in all number bases.
public static String decimalToBinary(int decimal) { StringBuilder binary = new StringBuilder(); while (decimal > 0) { int remainder = decimal % 2; binary.insert(0, remainder); decimal = decimal / 2; } return binary.toString(); }
// Function to convert decimal to octal
public static String decimalToOctal(int decimal) { StringBuilder octal = new StringBuilder(); while (decimal > 0) { int remainder = decimal % 8; octal.insert(0, remainder); decimal = decimal / 8; } return octal.toString(); }
// Function to convert decimal to hexadecimal
public static String decimalToHexadecimal(int decimal) { StringBuilder hexadecimal = new StringBuilder(); while (decimal > 0) { int remainder = decimal % 16; if (remainder < 10) hexadecimal.insert(0, remainder); else hexadecimal.insert(0, (char) ('A' + remainder - 10)); decimal = decimal / 16; } return hexadecimal.toString(); }
// Function to convert binary to decimal
public static int binaryToDecimal(String binary) { int decimal = 0; int power = 0; for (int i = binary.length() - 1; i >= 0; i--) { if (binary.charAt(i) == '1') { decimal += Math.pow(2, power); } power++; } return decimal; }
// Function to check if a string is a valid decimal
public static boolean isValidDecimal(String number) { for (int i = 0; i < number.length(); i++) { if (!Character.isDigit(number.charAt(i))) { return false; } } return true; }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask for the number and its type
System.out.print("Enter a number: "); String number = scanner.nextLine(); System.out.print("Enter the type of number (binary or decimal): "); String type = scanner.nextLine().toLowerCase();
// Check for validity of decimal number
if (type.equals("decimal")) { if (!isValidDecimal(number)) { System.out.println("Error: Not a valid decimal number!"); return; } }