Using Eclipse, create a Main class with the regular main method. In the class, t
ID: 3536146 • Letter: U
Question
Using Eclipse, create a Main class with the regular main method. In the class, there should be a method that converts a binary number represented as a string into a decimal integer. The method has the following signature:
public static int binaryToDecimal(String binaryString)
For example, the binary string 1001 is 9 (1 x 23 + 0 x 22 + 0 x 21 + 1 x 20). So, binaryToDecimal(“1001â€) returns 9. Note that Integer.parseInt(“1001â€, 2) parses a binary string to a decimal value, but you cannot use that method in this exercise.
The main method should prompt the user for a binary number and print out the corresponding decimal integer. Use javadoc to document to program, and make sure your name is in the documentation.
Explanation / Answer
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println(" Enter binary string ");
String binaryString = in.next();
System.out.println(binaryString + " and its equivalent decimal number is " + binaryToDecimal(binaryString ));
}
public static int binaryToDecimal(String binaryString)
{
double decimal=0;
for(int i=0;i<binaryString.length();i++)
{
if(binaryString.charAt(i)== '1')
{
decimal =decimal+ Math.pow(2,binaryString.length()-1-i);
}
}
return (int) decimal;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.