-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPractical_31.java
More file actions
42 lines (37 loc) · 1.46 KB
/
Practical_31.java
File metadata and controls
42 lines (37 loc) · 1.46 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
32
33
34
35
36
37
38
39
40
41
42
/* Question := 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. */
class NumberFormatException extends Exception{
public NumberFormatException(String message){
super(message);
}
}
public class Practical_31 {
public static int bin2Dec(String binaryString) throws NumberFormatException{
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString.charAt(i) != '0' && binaryString.charAt(i) != '1') {
throw new NumberFormatException("Input string is not a valid binary string.");
}
}
int decimal = 0;
int base = 1;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += base;
}
base *= 2;
}
return decimal;
}
public static void main(String[] args) {
String binaryString = "1010102";
try {
int decimal = bin2Dec(binaryString);
System.out.println("Binary string " + binaryString + " is equivalent to decimal number " + decimal);
}
catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
/* Output :=
Input string is not a valid binary string. */