30.2k views
2 votes
Write and test a bin2Dec(String binaryString) method to convert a binary string into a decimal number. Implement the bin2Dec method to throw a NumberFormatException if the string is not a binary string

User Mrry
by
5.7k points

1 Answer

6 votes

Answer:

Following are the method to this question:

import java.util.*;//import package for user input

public class Main //defining a class

{

public static int bin2Dec(String binaryString) throws NumberFormatException//defining a method bin2Dec that accept string value

{

int r=0,p= 1,i;

Stack<Integer> s = new Stack<>();//creating Stack object

for(i = binaryString.length()-1;i>=0;i--)//defining for loop to convert binary to decimal value

{

if(binaryString.charAt(i) != '0' && binaryString.charAt(i) != '1')//defining if block to check value

{

throw new NumberFormatException();//use throw block to check Exception

}

if(binaryString.charAt(i) == '1')//defining if block to check first input is value equal to 1

{

s.push(p);//using push method to add value in stack

}

p*= 2;//calculating the decimal value

}

while (!s.isEmpty())//defining while loop to stack is empty

{

r += s.pop();//use r variable to calculate value

}

return r;//return value

}

public static void main(String[] ax) //defining main method

{

Scanner oxb= new Scanner(System.in);//creating Scanner class object for input value

System.out.print("Enter a binary number: ");//print message

String b = oxb.nextLine();// defining String variable for input value

try //defining try block

{

System.out.print(bin2Dec(b));//use print method to call bin2Dec method

}

catch (Exception e)//use catch block to catch Exception

{

System.out.print(b+ "Not a binary number: ");//print message

}

}

}

output:

Enter a binary number: 101

5

Step-by-step explanation:

In the above-given code a method, "bin2Dec" is declared, that accept a string variable in its parameter, inside the method an integer variable and stack class object is created, and this method uses two loops, and in the for loop, it converts the binary to a decimal value, in the while loop it checks all value and adds its value in r variable.

In the main method, a scanner class object is created, that use a string variable to input value from the user-end, and use the try and catch block to call method.

User Shiboe
by
3.9k points