-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractical31.java
More file actions
31 lines (27 loc) · 1.27 KB
/
practical31.java
File metadata and controls
31 lines (27 loc) · 1.27 KB
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
// Write the bin2Dec (string binary String) method to convert a binary string into a decimal number. Implement the bin2Dec method to throw a NumberFormatException if the string is not a binary string.
import java.util.Scanner;
public class practical31 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a binary string: ");
String binaryString = sc.nextLine();
try {
int decimalValue = bin2Dec(binaryString);
System.out.println("The decimal equivalent of " + binaryString + " is: " + decimalValue);
} catch (NumberFormatException e) {
System.out.println("Exception: " + e.getMessage());
}
sc.close();
}
public static int bin2Dec(String binaryString) throws NumberFormatException {
int decimal = 0;
for (int i = 0; i < binaryString.length(); i++) {
char ch = binaryString.charAt(i);
if (ch != '0' && ch != '1') {
throw new NumberFormatException("Not a binary string: " + binaryString);
}
decimal = decimal * 2 + (ch - '0'); // Shift left by 1 (multiply by 2) and add the current bit
}
return decimal;
}
}