In: Computer Science
Implement the program as follows:
Program: DBConverter.java
import java.util.Scanner; /* import Scanner class */
public class DBConverter{ /* create a class DBConverter */
public static int binaryToDecimal(String binary){ /* define the method binaryToDecimal() */
int decimal = 0; /* initialize decimal to 0 */
int n = 0, i = binary.length()-1; /* initialize n=0, and i = length of binary -1 */
while(i>=0){ /* repeat until index i>= 0, iterate over each character from last to first */
int temp = Integer.parseInt(""+binary.charAt(i)); /* calculate the int value of each character */
decimal += temp*Math.pow(2, n); /* calculate its positional value and add to decimal value */
n++; /* increment n and decrement i */
i--;
}
return decimal; /* return decimal value */
}
public static String decimalToBinary(int decimal){ /* define the method decimalToBinary() */
String binary = ""; /* initialize binary to "" */
while(decimal>0){ /* repeat until decimal>0 */
binary = decimal%2 + binary; /* Prepend the remainder when decimal is divided by 2 to binary */
decimal = decimal/2; /* divide decimal by 2 */
}
return binary; /* return binary */
}
public static void main(String[] args){ /* define main() method */
Scanner scnr = new Scanner(System.in); /* initialize Scanner */
System.out.print("Enter a binary number : "); /* ask the user to enter a binary value and read input */
String binary = scnr.nextLine();
System.out.println("Decimal is " + binaryToDecimal(binary)); /* convert binary to decimal using binaryToDecimal() */
System.out.print("Enter a decimal number : "); /* ask the user to enter a decimal and read input */
int decimal = scnr.nextInt();
System.out.println("Binary is " + decimalToBinary(decimal)); /* convert decimal to binary using decimalToBinary() */
}
}
Screenshot:
Output:
Please don't forget to give a Thumbs Up.