Java Online Compiler
Example: Binary-Decimal Converter with User Input in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Binary-Decimal Converter with User Input import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Converts a binary string to its decimal equivalent. * @param binaryString The binary number as a string. * @return The decimal equivalent of the binary string. */ public static int binaryToDecimal(String binaryString) { int decimal = 0; int power = 0; for (int i = binaryString.length() - 1; i >= 0; i--) { char bit = binaryString.charAt(i); if (bit == '1') { decimal += Math.pow(2, power); } else if (bit != '0') { // Handle invalid binary input throw new IllegalArgumentException("Invalid binary string: " + binaryString); } power++; } return decimal; } /** * Converts a decimal integer to its binary string equivalent. * @param decimal The decimal number. * @return The binary string representation of the decimal number. */ public static String decimalToBinary(int decimal) { if (decimal == 0) { return "0"; } if (decimal < 0) { // For simplicity, handle only positive integers. For negative, Two's Complement is needed. throw new IllegalArgumentException("Negative numbers not supported for simple binary conversion."); } StringBuilder binaryBuilder = new StringBuilder(); int tempDecimal = decimal; while (tempDecimal > 0) { int remainder = tempDecimal % 2; binaryBuilder.append(remainder); tempDecimal /= 2; } return binaryBuilder.reverse().toString(); } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user for the type of conversion System.out.println("Choose conversion type:"); System.out.println("1. Binary to Decimal"); System.out.println("2. Decimal to Binary"); System.out.print("Enter your choice (1 or 2): "); int choice = scanner.nextInt(); // Step 3: Perform conversion based on user's choice try { if (choice == 1) { System.out.print("Enter a binary number: "); String binaryInput = scanner.next(); int decimalResult = binaryToDecimal(binaryInput); System.out.println("Decimal equivalent: " + decimalResult); } else if (choice == 2) { System.out.print("Enter a decimal number: "); int decimalInput = scanner.nextInt(); String binaryResult = decimalToBinary(decimalInput); System.out.println("Binary equivalent: " + binaryResult); } else { System.out.println("Invalid choice. Please enter 1 or 2."); } } catch (IllegalArgumentException e) { System.err.println("Error: " + e.getMessage()); } finally { // Step 4: Close the scanner to prevent resource leaks scanner.close(); } } }
Output
Clear
ADVERTISEMENTS