Answer:
import java.util.*;
public class BinaryToDecimal
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String binaryNumber;
int decimalNumber = 0;
System.out.print("Enter the binary number: ");
binaryNumber = input.nextLine();
for(int i=0; i<binaryNumber.length(); i++){
char c = binaryNumber.charAt(binaryNumber.length()-1-i);
int digit = Character.getNumericValue(c);
decimalNumber += (digit * Math.pow(2, i));
}
System.out.println(decimalNumber);
}
}
Step-by-step explanation:
Create a Scanner object to be able to get input from the user
Declare the variables
Ask the user to enter the binaryNumber as a String
Create a for loop that iterates through the binaryNumber. Get each character using charAt() method. Convert that character to an integer value using Character.getNumericValue(). Add the multiplication of integer value and 2 to the power of i to the decimalNumber variable (cumulative sum)
When the loop is done, print the decimalNumber variable