forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvertor.java
33 lines (28 loc) · 1.26 KB
/
convertor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Scanner;
public class BinaryDecimalConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Binary to Decimal and Decimal to Binary Converter");
System.out.print("Enter 1 to convert Binary to Decimal or 2 to convert Decimal to Binary: ");
int choice = scanner.nextInt();
if (choice == 1) {
System.out.print("Enter a binary number: ");
String binaryInput = scanner.next();
int decimalResult = binaryToDecimal(binaryInput);
System.out.println("Decimal result: " + decimalResult);
} else if (choice == 2) {
System.out.print("Enter a decimal number: ");
int decimalInput = scanner.nextInt();
String binaryResult = decimalToBinary(decimalInput);
System.out.println("Binary result: " + binaryResult);
} else {
System.out.println("Invalid choice. Please enter 1 for Binary to Decimal or 2 for Decimal to Binary.");
}
}
public static int binaryToDecimal(String binary) {
return Integer.parseInt(binary, 2);
}
public static String decimalToBinary(int decimal) {
return Integer.toBinaryString(decimal);
}
}