In: Computer Science
JAVA:
Write a program that converts a binary number to decimal (integer)
Based on user input: Ask user to input a binary number
Conditions:
Check that the binary number starts with a 1 and only has 0s and 1s
If condition is not met, ask for user to reenter a number
Conver the binary to decimal (integer)
Ask user if they want to input another number if not then the program will exit
*Please do not use built-in java functions when converting binary to decimal
Please go through screenshots for reference .And check line numbers according to line numbers in screenshot you can easily understand.Have any doubts comment below.Thank you.
JAVA CODE:
import java.util.*;
public class BinaryToDecimal {
public static void main(String args[])
{
System.out.print("Enter Binary
number:");
BinaryToDecimal.TakeInput();
}
public static void TakeInput() //Method to Take input
from user
{
Scanner sc = new
Scanner(System.in);
String number = sc.next(); //Taking
input from user
if(number.charAt(0)=='1') //
Condition to check number starts with 1 or not
{
int n =
Integer.parseInt(number);
int l = 0;
while(n>0) // Loop to check
number having only 0's or 1's
{
if(n%10==0 || n%10==1)
l++;
n=n/10;
}
if(l==number.length()) // if it is binary number pass the number to
convert to decimal
{
BinaryToDecimal.ToDecimal(Integer.parseInt(number));
}
else // number
is not binary ask user to reenter the number
{
System.out.print("reenter a number:");
BinaryToDecimal.TakeInput();
}
}
else // if number is not start with
1 ask user to reenter the number
{
System.out.println("reenter a number:");
BinaryToDecimal.TakeInput();
}
}
public static void ToDecimal(int num) // method to
change the binary number to decimal
{
int decimal=0,p=0;
while(num>0)
{
decimal +=
(num%10)*Math.pow(2,p);
num =
num/10;
p++;
}
System.out.println(decimal);
System.out.print("If you want to
input another number(y/n):"); // Ask user if you to enter another
number
Scanner sc1 = new
Scanner(System.in);
char ch =
sc1.next().charAt(0); // scaning character to y-for YES
and n-for NO
if(ch=='n') // if n (NO) EXIT form
program
{
System.exit(0);
}
else // if y (YES) ask user to
enter number
{
System.out.print("Enter the Binary number:");
BinaryToDecimal.TakeInput();
}
}
}



