-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_decimal.java
More file actions
25 lines (24 loc) · 1.19 KB
/
Binary_decimal.java
File metadata and controls
25 lines (24 loc) · 1.19 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
import javax.swing.JOptionPane;
public class Binary_decimal {
public static void main(String args[]) {
String binaryStr = JOptionPane.showInputDialog(null,
"Enter a binary number to transform it into a decimal number:",
"Conversion of binary numbers", JOptionPane.PLAIN_MESSAGE);
while (binaryStr.contains("1") == false && binaryStr.contains("0") == false) {
JOptionPane.showMessageDialog(null, "Please, enter a binary number.",
"Error", JOptionPane.WARNING_MESSAGE);
binaryStr = JOptionPane.showInputDialog(null,
"Enter a binary number to transform it into a decimal number:",
"Conversion of binary numbers", JOptionPane.PLAIN_MESSAGE);
}
int len = binaryStr.length();
int result = 0;
for (int i = len - 1; i >= 0; i--) {
char digit = binaryStr.charAt(i);
int digitValue = Character.getNumericValue(digit);
result += digitValue * Math.pow(2, len - 1 - i);
}
JOptionPane.showMessageDialog(null, "The binary number in decimal is: " + result, "Result",
JOptionPane.PLAIN_MESSAGE);
}
}