Write the bin2Dec (String binaryString) method to convert a binary string into a
ID: 3796386 • 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 bin20ec method to throw a Number Format Exception if the string is not a binary string. Test your method in a grog ram 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 pros ram catch it and print Not a binary string "before terminating.Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class Test{
public static int bin2Dec(String binaryString){
double j=0;
for(int i=0;i<binaryString.length();i++){
if(binaryString.charAt(i) != '1' && binaryString.charAt(i) != '0')
throw new NumberFormatException();
if(binaryString.charAt(i)== '1'){
j=j+ Math.pow(2,binaryString.length()-1-i);
}
}
return (int) j;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a binary string: ");
String binaryString = sc.next();
try{
System.out.println("Decimal : "+bin2Dec(binaryString));
}catch(NumberFormatException e){
System.out.println("Not a binary string");
}
}
}
/*
Sample run:
Enter a binary number: 1001
Decimal : 9
Enter a binary number: 111111
Decimal : 63
Enter a binary string: 123dew
Not a binary string
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.