Use java Write a program which will convert a binary number to decimal, or cover
ID: 3844458 • Letter: U
Question
Use java
Write a program which will convert a binary number to decimal, or covert a decimal number to binary. You will present a menu to the user with the following options: (Convert Binary to Decimal, Convert Decimal to Binary, Exit the program.). For option 1, you will ask the user for a string of 0's and 1's and you will need to take this string and convert it from the binary number that it represents, to the decimal value. For option 2 you will ask the user for a decimal (base 10) number and convert the number to a binary number. Requirements: You are NOT allowed to use any built in Java methods to do the conversions. You must use loops to mathematically calculate the conversions. Your program must loop continuously until the user chooses to exit. You must validate the menu choice, and if the user chooses an incorrect menu option, display an error message and allow them to Sample Output: Enter your menu choice (1 - 3): 1 Enter the binary string: 10111111100011010000 10111111100011010000 in decimal is 784592 Enter your menu choice (1 - 3): 2 Enter the decimal number: 4567876543456789876 4567876543456789876 in binary is: 11111101100100010110111000001110111110100101001100010101110100Explanation / Answer
import java.util.Scanner; public class Conversion { private static Scanner sc = new Scanner(System.in); public static void main(String args[]) { boolean flag = true; do { System.out.println("Binary Number Converter"); System.out.println("1. Covert Binary to Decimal"); System.out.println("2. Covert Decimal to Binary"); System.out.println("3. Exit the program"); System.out.println("Enter your choice(1-3): "); System.out.println("Enter your choice(1-3): "); int choice = sc.nextInt(); switch (choice) { case 1: convertBinaryToDecimal(); break; case 2: convertDecimalToBinary(); break; case 3: flag = false; break; default: System.out.println("Invalid input!!!"); } } while (flag); } private static void convertBinaryToDecimal() { System.out.println("Enter the binary String"); String input = sc.next(); long number = 0; int lenth = input.length(); for (int i = lenth - 1; i >= 0; i--) { if (input.charAt(i) == '1') { number = number + (long) (Math.pow((double) 2, (double) lenth - i - 1)); } } System.out.println(number); } private static void convertDecimalToBinary() { System.out.println("Enter the Decimal Number"); long input = sc.nextLong(); String binary = ""; while (input != 0) { long r = input % 2; binary = Long.toString(r) + binary; input = input/2; } System.out.println(binary); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.