/*
Enter a binary string: wx1234
The string must be 0 or 1.
Enter a binary string: 1234
The string must be 0 or 1.
Enter a binary string: 10001
17
*/
import java.util.Scanner;
publicclass BinaryToDecimal {
publicstaticvoidmain(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary string: ");
String b = input.nextLine();
for (int i = 0; i < b.length(); i++) {
if (!Character.isDigit(b.charAt(i)) || b.charAt(i) > '1') {
System.out.println("The string must be 0 or 1.");
System.exit(0);
}
}
System.out.println(toDecimal(b));
}
publicstaticinttoDecimal(String b) {
int decimalValue = 0;
for (int i = 0; i < b.length(); i++)
decimalValue = decimalValue * 2 + binaryToDecimal(b.charAt(i));
return decimalValue;
}
publicstaticintbinaryToDecimal(char ch) {
return ch - 48; // 0的ASCII码是48
}
}