Write the bin2Dec(String binaryString) method to convert a binary string into a
ID: 3815131 • Letter: W
Question
Write the bin2Dec(String binaryString) method to convert a binary string into a decimal number (your method should return an integer). Implement the bin2Dec method to throw a NumberFormatException if the string is not a binary string. Test your method in a program that prompts the user to input a binary string and uses your bin2Dec method to print out the decimal equivalent of that string. If the method throws an error, have your program catch it and print "Not a binary string, " before terminating. Enter a binary string: 1011000101 709Explanation / Answer
NumberFormat.java
import java.util.Scanner;
public class NumberFormat{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try{
System.out.println("Enter a binary string:");
String s = scan.next();
int integerValue = bin2Dec(Integer.parseInt(s));
System.out.println("The decimal value of "+s+" is "+integerValue);
}
catch(NumberFormatException e){
System.out.println(e);
}
}
public static int bin2Dec(int binaryNumber) throws NumberFormatException{
int decimal = 0;
int p = 0;
try{
while(true){
if(binaryNumber == 0){
break;
} else {
int temp = binaryNumber%10;
decimal += temp*Math.pow(2, p);
binaryNumber = binaryNumber/10;
p++;
}
}
}
catch(NumberFormatException e){
throw new NumberFormatException("Invalid binary number");
}
return decimal;
}
}
Output:
Enter a binary string:
1011000101
The decimal value of 1011000101 is 709
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.