Answer to Question #20708 in AJAX | JavaScript | HTML | PHP for rahilpathan

Question #20708
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");
}
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS