-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberFormatException
More file actions
35 lines (27 loc) · 1004 Bytes
/
NumberFormatException
File metadata and controls
35 lines (27 loc) · 1004 Bytes
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
package taoshiflex.lab8;
import java.util.Scanner;
public class Lab8 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a binary string: ");
String binaryString = scan.nextLine();
try {
int decimalValue = bin2Dec(binaryString);
System.out.println("Decimal value: " + decimalValue);
}
catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
}
scan.close();
}
public static int bin2Dec(String binaryString) throws NumberFormatException {
// Check if the string is a valid binary string
for (char c : binaryString.toCharArray()) {
if (c != '0' && c != '1') {
throw new NumberFormatException("Input is not a binary string.");
}
}
// Convert binary string to decimal
return Integer.parseInt(binaryString, 2);
}
}