Write a Java program that will accept an integer containing only 0s and 1s (i.e. a “binary”
integer) as input and display its decimal equivalent. If user entered 1001, the program
will display 9. If user entered 1211, an error message should be displayed.
1
Expert's answer
2012-12-19T10:00:35-0500
import java.util.Scanner; public class BinaryNumber { public static void main(String... args) { Scanner scanner = newScanner(System.in); System.out.print(">"); String in = scanner.nextLine(); try { int value =Integer.parseInt(in, 2); System.out.print(value); } catch (NumberFormatExceptionex) { System.out.print("an invalid value"); } } }
Comments
Leave a comment