Write a Java program named BinaryConversion that will convert base 2 numbers to base 10 numbers. The data for this program will be entered from the keyboard using JOptionPane one 16-bit binary number at a time. Note that each base 2 number is actually read in as a String. The program should continue until a 16-bit base 2 number consisting of all 0’s is entered. Once the 16-bit number has been entered your program should make sure that the input is valid, that is, make sure that it has 16 bits and make sure that there are no digits other than 0 and 1 in the input. If the input is invalid an appropriate message should be printed, the current, invalid, 16-bit base 2 number should not be converted, and your program should ask for a new 16-bit number. Now that you’ve got a valid 16-bit base 2 number (remember that it’s actually a String) loop through the number to convert it to base 10. You must process each binary number digit by digit. No built-in conversion functions allowed. Your program should print the output in a message dialog or the terminal window.
Sample input/output:
Enter a 16-bit binary number.
1111000011110000
Base 2: 1111000011110000
Base 10: 61680
enter a 16-bi binary number.
0000000000000000
Program Terminating
*NOTE* Please use only void main method, if while and for statements. Please do not use the mathpow and the boolean is valid thing
SOLUTION- I have solve the problem in Java code screenshot for easy understanding :) CODE- //java code import javax.swing.*; public class BinToDec { //main method public static void main(String[] args) { String bin; int dec = 0; do { bin = JOptionPane.showInputDialog("Enter a 16-bit binary number."); dec = 0; int power = 1; for (int i = bin.length() - 1; i >= 0; i--) { if (bin.charAt(i) == '1') { dec += power; } else if (bin.charAt(i) == '0') { } else { System.out.println("Error: Entered binary " + bin + " is invalid binary number."); dec = -1; break; } power *= 2; } if (dec != 0 && dec != -1) { System.out.println("Base 2: " + bin); System.out.println("Base 10: " + dec + "\n"); } } while (dec != 0); System.out.println("Program Terminating"); } }
SCREENSHOT -
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------
Get Answers For Free
Most questions answered within 1 hours.